如何计算多个秒表时间的平均值?

时间:2016-10-21 16:46:05

标签: c# stopwatch

所以基本上我要做的就是计算我的for循环生成的所有Stop Watch时间的平均值,并将其输出到控制台。我知道如何取平均值,但我不知道如何将它应用于秒表时间。请帮帮忙?

for (int index = 0; index < iterations; index++)
        {
            // loop to generate an array of random numbers      
            for (int count = 0; count < arrayOfInts.Length; count++)
            {
                arrayOfInts[count] = r.Next(numitems);
            }
            // a random array has been created start the clock and sort it
            Stopwatch elpased = new Stopwatch();
            elpased.Start();
            selectionSort(arrayOfInts);
            elpased.Stop();

            if (iterations == iterations) 
            {

                var average = elpased.Elapsed;

                Console.WriteLine ("Time for ___ sort to complete: " + elpased.Elapsed.ToString ());
            }
            }



            Console.ReadLine();
    }

这是我到目前为止所做的。

1 个答案:

答案 0 :(得分:3)

我建议改用ElapsedTicks。并且您需要存储每次迭代的刻度并计算之后的平均值:

List<long> ticks = new List<long>();
for (int index = 0; index < iterations; index++)
{
    // loop to generate an array of random numbers      
    for (int count = 0; count < arrayOfInts.Length; count++)
    {
        arrayOfInts[count] = r.Next(numitems);
    }

    // a random array has been created start the clock and sort it
    Stopwatch elapsed = new Stopwatch();
    elapsed.Start(); 
    selectionSort(arrayOfInts);
    elpased.Stop();
    ticks.Add(elapsed.ElapsedTicks);
}

double avg = ticks.Average(); // create average of ticks
TimeSpan averageTimeSpan = new TimeSpan((long)avg); // cast needed from double to long

有一种更优雅的方式来生成随机数字阵列:

arrayOfInts = Enumerable.Range(0, count).Select(i => r.Next(numitems)).ToArray();

因为LINQ使用延迟执行,你甚至可以预先声明这个“查询”并在迭代中调用ToArray()

List<long> ticks = new List<long>();
IEnumerable<int> randomQuery = Enumerable.Range(0, count).Select(i => r.Next(numitems));

for (int index = 0; index < iterations; index++)
{
     //creates NEW random numbers each time, because of deferred execution
     arrayOfInts = randomQuery.ToArray(); 

     ...

另一个建议是让Stopwatch衡量整个时间,并将结果除以iterationsStopwatch可以恢复:

IEnumerable<int> randomQuery = Enumerable.Range(0, count).Select(i => r.Next(numitems));
Stopwatch elapsed = new Stopwatch(); // only ONE instance needed
for (int index = 0; index < iterations; index++)
{
     arrayOfInts = randomQuery.ToArray();
     elapsed.Start(); // resumes without a reset
     selectionSort(arrayOfInts);
     elpased.Stop();
}
TimeSpan averageTimeSpan = new TimeSpan(elapsed.ElapsedTicks/iterations);