.NET 4.x Как заставить функцию работать быстрее? - C#
Формулировка задачи:
Может кто подсказать в плане оптимизации как заставить функцию Check() работать быстрее? Применил StringBilder вместо string, код стал работать в 3 раза быстрее. Может кто еще каких идей подкинет?
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Windows.Forms;
- using System.Diagnostics;
- using System.IO;
- namespace PA_Hard
- {
- public partial class Form1 : Form
- {
- public Form1()
- {
- InitializeComponent();
- button1.Enabled = false;
- Form1.CheckForIllegalCrossThreadCalls = false;
- }
- static bool flag = true;
- string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
- int length_pass = 1;
- StringBuilder pass = new StringBuilder();
- public void Check()
- {
- ulong number_of_combinations = 0;
- Stopwatch st = new Stopwatch();
- st.Start();
- while (flag)
- {
- StringBuilder result = new StringBuilder();
- int[] index = new int[length_pass];
- bool finish = true;
- while (finish)
- {
- number_of_combinations++;
- for (int i = 0; i < index.Length; i++)
- {
- result.Append(alphabet[index[i]]);
- }
- if (result.Equals(pass))
- {
- flag = false;
- st.Stop();
- richTextBox1.Text = "Пароль " + result + "\nПодобран с " + number_of_combinations.ToString() + " комбинации\nВремя затрачено " + st.Elapsed.TotalSeconds.ToString();
- break;
- }
- result.Clear();
- index[index.Length - 1]++;
- for (int i = (index.Length - 1); i >= 0; i--)
- {
- if (index[i] > (alphabet.Length - 1))
- {
- index[i] = 0;
- if (--i < 0)
- {
- finish = false;
- break;
- }
- index[i]++;
- i++;
- }
- }
- }
- length_pass++;
- }
- flag = true;
- length_pass = 1;
- number_of_combinations = 0;
- }
- private void button1_Click(object sender, EventArgs e)
- {
- Thread ChechThread = new Thread(Check);
- ChechThread.IsBackground = true;
- ChechThread.Start();
- }
- private void textBox1_TextChanged(object sender, EventArgs e)//Проверочка на корректный ввод
- {
- int i = 0;
- try
- {
- if (textBox1.Text[i] != null)// Попробую вызвать исключение с индексом
- {
- i++;
- }
- }
- catch (IndexOutOfRangeException)
- {
- //break; //ничего не ввели в поле
- }
- if (i > 0)
- {
- i = 0;
- pass.Clear();
- while (true)
- {
- try
- {
- if ((Convert.ToInt32(textBox1.Text[i]) >= 48 && Convert.ToInt32(textBox1.Text[i]) <= 57) ||
- (Convert.ToInt32(textBox1.Text[i]) >= 65 && Convert.ToInt32(textBox1.Text[i]) <= 90) ||
- (Convert.ToInt32(textBox1.Text[i]) >= 97 && Convert.ToInt32(textBox1.Text[i]) <= 122))
- {
- button1.Enabled = true;
- pass.Append(textBox1.Text[i]);
- richTextBox1.Text = "Пароль задан верно\n";
- }
- else
- {
- button1.Enabled = false;
- richTextBox1.Text = "Присутстуют неккоректные символы\n";
- break;
- }
- i++;
- }
- catch (IndexOutOfRangeException)
- {
- break;
- }
- }
- }
- else
- {
- button1.Enabled = false;
- richTextBox1.Text = "Введите хотя бы один символ\n";
- }
- }
- }
- }
форум умер.
Решение задачи: «.NET 4.x Как заставить функцию работать быстрее?»
textual
Листинг программы
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Diagnostics;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows.Forms;
- namespace WindowsFormsApplication1
- {
- public partial class Form1 : Form
- {
- string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
- StringBuilder pass = new StringBuilder();
- public Form1()
- {
- InitializeComponent();
- }
- private async void button1_Click(object sender, EventArgs e)
- {
- var context = SynchronizationContext.Current;
- await Task.Run(() => Check(context));
- }
- public void Check(SynchronizationContext context)
- {
- Stopwatch st = new Stopwatch();
- st.Start();
- int LEN_ABC = alphabet.Length - 1;
- int combinationsCounter = 0;
- int passLength = 0;
- Parallel.For(1, 100, new ParallelOptions {MaxDegreeOfParallelism = 3} , (_p, loopState) =>
- {
- StringBuilder result = new StringBuilder();
- int length_pass = Interlocked.Increment(ref passLength);
- int[] index = new int[length_pass];
- int LEN = length_pass - 1;
- while (!loopState.IsStopped) {
- int combination = Interlocked.Increment(ref combinationsCounter);
- for (int i = 0; i < length_pass; i++) {
- result.Append(alphabet[index[i]]);
- }
- if (result.Equals(pass)) {
- st.Stop();
- context.Post((_) =>
- {
- mainLabel.Text = "Пароль " + result + "\nПодобран с " +
- combination + " комбинации\nВремя затрачено " +
- st.Elapsed.TotalSeconds.ToString();
- }, null);
- loopState.Stop();
- break;
- }
- result.Clear();
- index[LEN]++;
- for (int i = LEN; i > 0; i--) {
- if (index[i] > LEN_ABC) {
- index[i] = 0;
- index[i - 1]++;
- }
- }
- //
- if (index[0] > LEN_ABC) {
- index[0] = 0;
- break;
- }
- }
- });
- }
- private void textBox1_TextChanged(object sender, EventArgs e)
- {
- if (string.IsNullOrWhiteSpace(textBox1.Text)) {
- button1.Enabled = false;
- mainLabel.Text = "Введите хотя бы один символ\n";
- return;
- }
- pass.Clear();
- for (int i = 0; i < textBox1.Text.Length; i++) {
- int Num = Convert.ToInt32(textBox1.Text[i]);
- if ((Num > 47 && Num < 58) || // Цифры
- (Num > 64 && Num < 91) || // Прописные
- (Num > 96 && Num < 123)) // Строчные
- {
- button1.Enabled = true;
- pass.Append(textBox1.Text[i]);
- mainLabel.Text = "Пароль задан верно\n";
- } else {
- button1.Enabled = false;
- mainLabel.Text = "Присутстуют неккоректные символы\n";
- break;
- }
- }
- }
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д