.NET 4.x Как заставить функцию работать быстрее? - C#

Узнай цену своей работы

Формулировка задачи:

Может кто подсказать в плане оптимизации как заставить функцию Check() работать быстрее? Применил StringBilder вместо string, код стал работать в 3 раза быстрее. Может кто еще каких идей подкинет?
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Windows.Forms;
  10. using System.Diagnostics;
  11. using System.IO;
  12. namespace PA_Hard
  13. {
  14. public partial class Form1 : Form
  15. {
  16. public Form1()
  17. {
  18. InitializeComponent();
  19. button1.Enabled = false;
  20. Form1.CheckForIllegalCrossThreadCalls = false;
  21. }
  22. static bool flag = true;
  23. string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  24. int length_pass = 1;
  25. StringBuilder pass = new StringBuilder();
  26. public void Check()
  27. {
  28. ulong number_of_combinations = 0;
  29. Stopwatch st = new Stopwatch();
  30. st.Start();
  31. while (flag)
  32. {
  33. StringBuilder result = new StringBuilder();
  34. int[] index = new int[length_pass];
  35. bool finish = true;
  36. while (finish)
  37. {
  38. number_of_combinations++;
  39. for (int i = 0; i < index.Length; i++)
  40. {
  41. result.Append(alphabet[index[i]]);
  42. }
  43. if (result.Equals(pass))
  44. {
  45. flag = false;
  46. st.Stop();
  47. richTextBox1.Text = "Пароль " + result + "\nПодобран с " + number_of_combinations.ToString() + " комбинации\nВремя затрачено " + st.Elapsed.TotalSeconds.ToString();
  48. break;
  49. }
  50. result.Clear();
  51. index[index.Length - 1]++;
  52. for (int i = (index.Length - 1); i >= 0; i--)
  53. {
  54. if (index[i] > (alphabet.Length - 1))
  55. {
  56. index[i] = 0;
  57. if (--i < 0)
  58. {
  59. finish = false;
  60. break;
  61. }
  62. index[i]++;
  63. i++;
  64. }
  65. }
  66. }
  67. length_pass++;
  68. }
  69. flag = true;
  70. length_pass = 1;
  71. number_of_combinations = 0;
  72. }
  73. private void button1_Click(object sender, EventArgs e)
  74. {
  75. Thread ChechThread = new Thread(Check);
  76. ChechThread.IsBackground = true;
  77. ChechThread.Start();
  78. }
  79. private void textBox1_TextChanged(object sender, EventArgs e)//Проверочка на корректный ввод
  80. {
  81. int i = 0;
  82. try
  83. {
  84. if (textBox1.Text[i] != null)// Попробую вызвать исключение с индексом
  85. {
  86. i++;
  87. }
  88. }
  89. catch (IndexOutOfRangeException)
  90. {
  91. //break; //ничего не ввели в поле
  92. }
  93. if (i > 0)
  94. {
  95. i = 0;
  96. pass.Clear();
  97. while (true)
  98. {
  99. try
  100. {
  101. if ((Convert.ToInt32(textBox1.Text[i]) >= 48 && Convert.ToInt32(textBox1.Text[i]) <= 57) ||
  102. (Convert.ToInt32(textBox1.Text[i]) >= 65 && Convert.ToInt32(textBox1.Text[i]) <= 90) ||
  103. (Convert.ToInt32(textBox1.Text[i]) >= 97 && Convert.ToInt32(textBox1.Text[i]) <= 122))
  104. {
  105. button1.Enabled = true;
  106. pass.Append(textBox1.Text[i]);
  107. richTextBox1.Text = "Пароль задан верно\n";
  108. }
  109. else
  110. {
  111. button1.Enabled = false;
  112. richTextBox1.Text = "Присутстуют неккоректные символы\n";
  113. break;
  114. }
  115. i++;
  116. }
  117. catch (IndexOutOfRangeException)
  118. {
  119. break;
  120. }
  121. }
  122. }
  123. else
  124. {
  125. button1.Enabled = false;
  126. richTextBox1.Text = "Введите хотя бы один символ\n";
  127. }
  128. }
  129. }
  130. }
форум умер.

Решение задачи: «.NET 4.x Как заставить функцию работать быстрее?»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Drawing;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Windows.Forms;
  12.  
  13. namespace WindowsFormsApplication1
  14. {
  15.     public partial class Form1 : Form
  16.     {
  17.         string alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  18.         StringBuilder pass = new StringBuilder();
  19.  
  20.         public Form1()
  21.         {
  22.             InitializeComponent();
  23.         }
  24.  
  25.         private async void button1_Click(object sender, EventArgs e)
  26.         {
  27.             var context = SynchronizationContext.Current;
  28.             await Task.Run(() => Check(context));
  29.         }
  30.  
  31.         public void Check(SynchronizationContext context)
  32.         {
  33.             Stopwatch st = new Stopwatch();
  34.             st.Start();
  35.             int LEN_ABC = alphabet.Length - 1;
  36.             int combinationsCounter = 0;
  37.             int passLength = 0;
  38.  
  39.             Parallel.For(1, 100, new ParallelOptions {MaxDegreeOfParallelism = 3} , (_p, loopState) =>
  40.             {
  41.                 StringBuilder result = new StringBuilder();
  42.                 int length_pass = Interlocked.Increment(ref passLength);
  43.                 int[] index = new int[length_pass];
  44.                 int LEN = length_pass - 1;
  45.  
  46.                 while (!loopState.IsStopped) {
  47.                     int combination = Interlocked.Increment(ref combinationsCounter);
  48.  
  49.                     for (int i = 0; i < length_pass; i++) {
  50.                         result.Append(alphabet[index[i]]);
  51.                     }
  52.                     if (result.Equals(pass)) {
  53.                         st.Stop();
  54.                         context.Post((_) =>
  55.                         {
  56.                             mainLabel.Text = "Пароль " + result + "\nПодобран с " +
  57.                                              combination + " комбинации\nВремя затрачено " +
  58.                                              st.Elapsed.TotalSeconds.ToString();
  59.                         }, null);
  60.                         loopState.Stop();
  61.                         break;
  62.                     }
  63.                     result.Clear();
  64.                     index[LEN]++;
  65.                     for (int i = LEN; i > 0; i--) {
  66.                         if (index[i] > LEN_ABC) {
  67.                             index[i] = 0;
  68.                             index[i - 1]++;
  69.                         }
  70.                     }
  71.                         //
  72.                         if (index[0] > LEN_ABC) {
  73.                         index[0] = 0;
  74.                         break;
  75.                     }
  76.                 }
  77.             });
  78.         }
  79.  
  80.         private void textBox1_TextChanged(object sender, EventArgs e)
  81.         {
  82.             if (string.IsNullOrWhiteSpace(textBox1.Text)) {
  83.                 button1.Enabled = false;
  84.                 mainLabel.Text = "Введите хотя бы один символ\n";
  85.                 return;
  86.             }
  87.             pass.Clear();
  88.  
  89.             for (int i = 0; i < textBox1.Text.Length; i++) {
  90.                 int Num = Convert.ToInt32(textBox1.Text[i]);
  91.  
  92.                 if ((Num > 47 && Num < 58) || // Цифры
  93.                     (Num > 64 && Num < 91) || // Прописные
  94.                     (Num > 96 && Num < 123))   // Строчные
  95.                 {
  96.                     button1.Enabled = true;
  97.                     pass.Append(textBox1.Text[i]);
  98.                     mainLabel.Text = "Пароль задан верно\n";
  99.                 } else {
  100.                     button1.Enabled = false;
  101.                     mainLabel.Text = "Присутстуют неккоректные символы\n";
  102.                     break;
  103.                 }
  104.             }
  105.         }
  106.     }
  107. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 3.4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы