计算for循环的大概运行时间

纳赛尔·萨迪吉

我的C#Windows窗体应用程序中有一段代码如下:

List<string> RESULT_LIST = new List<string>();
int[] arr = My_LIST.ToArray();

string s = "";

Stopwatch sw = new Stopwatch();
sw.Start();

for (int i = 0; i < arr.Length; i++)
{
  int counter = i;
  for (int j = 1; j <= arr.Length; j++)
  {
    counter++;
    if (counter == arr.Length)
    {
      counter = 0;
    }
    s += arr[counter].ToString();
    RESULT_LIST.Add(s);
  }
  s = "";
}
sw.Stop();
TimeSpan ts = sw.Elapsed;
string elapsedTime = String.Format("{0:00}", ts.TotalMilliseconds * 1000);
MessageBox.Show(elapsedTime);

我使用此代码来获取“我的列表”中数字的任意组合。我对My_LIST的行为就像递归的那样下图非常清楚地说明了我的目的:

在此处输入图片说明

我需要做的就是:

编写一个公式来计算这两个嵌套的for循环的大概运行时间,以猜测任意长度的运行时间,并帮助用户知道他/她必须等待的大概时间。

I have used a C# Stopwatch like this: Stopwatch sw = new Stopwatch(); to show the run time and below are the results(Note that in order to reduce the chance of error I've repeated the calculation three times for each length and the numbers show the time in nano seconds for the first, second and third attempt respectively.):

  1. arr.Length = 400; 127838 - 107251 - 100898
  2. arr.Length = 800; 751282 - 750574 - 739869
  3. arr.Length = 1200; 2320517 - 2136107 - 2146099
  4. arr.Length = 2000; 8502631 - 7554743 - 7635173

Note that there are only one-digit numbers in My_LIST to make the time of adding numbers to the list approximately equal.

How can I find out the relation between arr.Length and run time?

Eric Lippert

First, let's suppose you have examined the algorithm and noticed that it appears to be quadratic in the array length. This suggests to us that the time taken to run should be a function of the form

t = A + B n + C n2

You've gathered some observations by running the code multiple times with different values for n and measuring t. That's a good approach.

The question now is: what are the best values for A, B and C such that they match your observations closely?

This problem can be solved in a variety of ways; I would suggest to you that the least-squares method of regression would be the place to start, and see if you get good results. There's a page on it here:

www.efunda.com/math/leastsquares/lstsqr2dcurve.cfm


更新:我只是再次查看了您的算法,并意识到它是三次的,因为您在内部循环中有一个二次字符串concat。因此,此技术可能效果不佳。我建议您使用StringBuilder来使算法成为二次方。


现在,假设您事先知道问题是二次的。那么您将如何确定公式?一个好的开始是在对数刻度纸上画出您的观点。如果它们大致形成一条直线,则直线的斜率将为您提供多项式的幂的线索。如果它们没有形成一条直线-那么,当您到达桥时,越过那座桥。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章