2015-05-24 95 views
3

我想在C#中計算冒泡排序算法的時間。但它總是給出0.這是我的代碼。如何獲得以毫秒爲單位的時間?

public void bubbleSort(int[] arr, ref double time) 
{ 
    var sp = new Stopwatch(); 
    sp.Start(); 
    int temp = 0; 

    for (int i = 0; i < arr.Length; i++) 
    { 
      for (int sort = 0; sort < arr.Length - 1; sort++) 
      { 
       if (arr[sort] > arr[sort + 1]) 
       { 
        temp = arr[sort + 1]; 
        arr[sort + 1] = arr[sort]; 
        arr[sort] = temp; 
       } 
     } 
    } 
    sp.Stop(); 

    time = sp.Elapsed.Milliseconds*1000; 
} 

主要的時間總是0.我在這段代碼中犯了什麼錯誤。

+0

您是否調試過代碼並查看「毫秒」值? –

+1

如果你的數組不是很大,那麼你的算法可能需要不到1ms的時間來執行。 –

+0

通常,爲了衡量時間,您運行algortithm數千次或數百萬次,因爲通常一次迭代花費的時間太少以至於無法測量。 – Alejandro

回答

5

當你Milliseconds,你只得到毫秒的時間組件。因此,1.0501s只會被列爲50ms,而不是1050.1ms。此外,由於這返回int,您將而不是看到分數毫秒,這可能是這樣一個短的algorythm的情況。

取而代之,使用TotalMilliseconds,它將返回以毫秒爲單位的整個時間,以及重新調整包含小數部分的double

+1

是的它的工作總毫秒 – Hiba

3

您需要使用TotalMilliseconds財產

獲取整數和分數毫秒錶示目前時間跨度結構的價值。

time = sp.Elapsed.TotalMilliseconds * 1000; 
+1

謝謝.... 它的工作就像冠軍 – Hiba

相關問題