2016-10-21 68 views
-1

所以基本上我想要做的是計算所有停止監視時間的平均值,我的for循環產生並將其放到控制檯。我知道如何取平均值,但我不知道如何將其應用於秒錶時間。請幫忙?如何計算多個秒錶時間的平均值?

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(); 
    } 

這是我到目前爲止。

+2

什麼時候'iterations == iterations'永遠是假的? – zzzzBov

+0

可能重複的[查找平均時間集合](http://stackoverflow.com/questions/8847679/find-average-of-collection-of-timespans) –

+0

你說你知道如何取平均值,實際上並沒有取平均水平。 – Brandon

回答

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測量整個時間和iterations劃分結果。 Stopwatch es可以恢復:

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); 
+0

非常感謝,我對其進行了修改以解決我的需求。 –

+0

我試圖做類似的事情,但得到的數字報道,只是沒有意義。原因是[Elapsed.Ticks]應該用來代替'ElapsedTicks'因爲[在這裏]描述的原因(http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/12/c.net-little-pitfalls-stopwatch-蜱 - 是 - 不入庫時間 - ticks.aspx)。 – Ocelot20