2012-04-11 53 views
30

我想看看函數運行了多長時間。所以我添加了一個計時器對象我的形式,我想出了這個代碼:如何測量函數運行的時間?

private int counter = 0; 

// Inside button click I have: 
timer = new Timer(); 
timer.Tick += new EventHandler(timer_Tick); 
timer.Start(); 
Result result = new Result(); 
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia); 
timer.Stop(); 

和:

private void timer_Tick(object sender, EventArgs e) 
{ 
    counter++; 
    btnTabuSearch.Text = counter.ToString(); 
} 

不過這還不算什麼。爲什麼?

+0

如果設置timer.stop()的時間;開始()後正常。何時需要停止定時器?功能完成後? – 2012-04-11 13:44:24

+3

爲什麼不是秒錶? (http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) – VJAI 2012-04-11 13:46:41

+0

[測量代碼執行時間]的可能重複(https://stackoverflow.com/questions/16376191/measuring-代碼執行時間) – 2017-06-19 03:37:49

回答

40

爲了避免與定時器未來的問題,這裏是正確的代碼:

timer = new Timer(); 
timer.Tick += new EventHandler(timer_Tick); 
timer.Interval = 1; //set interval on 1 milliseconds 
timer.Enabled = true; //start the timer 
Result result = new Result(); 
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia); 
timer.Enabled = false; //stop the timer 

private void timer_Tick(object sender, EventArgs e) 
{ 
    counter++; 
    btnTabuSearch.Text = counter.ToString(); 
} 

但這是錯誤的形式給出。您必須使用Stopwatch (System.Diagnostic)類,因爲它是一個高分辨率計時器字診斷說的一切。

那麼試試這個:

Stopwatch timer = Stopwatch.StartNew(); 

Result result = new Result(); 
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia); 

timer.Stop(); 
TimeSpan timespan = timer.Elapsed; 

btnTabuSearch.Text = String.Format("{0:00}:{1:00}:{2:00}", timespan.Minutes, timespan.Seconds, timespan.Milliseconds/10); 
+4

注意:設置間隔爲1ms的計時器時,應注意不要認爲計數器實際上是毫秒數。取決於硬件,計時器(在我的電腦上)的最小間隔大約爲15毫秒。所以即使您將間隔設置爲1ms,它也會每15ms左右觸發一次。 – 2012-04-11 14:14:40

+0

明天我會試一試定時器。我只想要一個計數器來查看自從按下按鈕以來經過了多少時間。 – 2012-04-11 19:37:48

+1

'var timer = Stopwatch.StartNew();'< - 少一行代碼 – 2013-01-31 17:18:12

10

查看代碼運行時間的最佳方式是使用System.Diagnostics.Stopwatch

下面是一個例子:

using System.Diagnostics; 

#if DEBUG 
    Stopwatch timer = new Stopwatch(); 
    timer.Start(); 
#endif 

    //Long running code 

#if DEBUG 
    timer.Stop(); 
    Debug.WriteLine("Time Taken: " + timer.Elapsed.TotalMilliseconds.ToString("#,##0.00 'milliseconds'")); 
#endif 

我用#if DEBUG確保秒錶代碼不會進入產能釋放,但你可以沒有它。

43

請勿使用定時器 - 使用Stopwatch類。

var sw = new Stopwatch(); 
Result result = new Result(); 

sw.Start(); 
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia); 

sw.Stop(); 

// sw.Elapsed tells you how much time passed 
+7

甚至'var sw = Stopwatch.StartNew();'< - 少一行代碼 – 2013-01-31 17:19:03

6

對於時間的函數,你應該使用Stopwatch Class

而且,你的計時器不計的原因是因爲你沒有設置的時間間隔爲它。

7

使用System.Diagnostics程序的Stopwatch

static void Main(string[] args) 
{ 
    Stopwatch stopWatch = new Stopwatch(); 
    stopWatch.Start(); 
    Thread.Sleep(10000); 
    stopWatch.Stop(); 

    // Get the elapsed time as a TimeSpan value. 
    TimeSpan ts = stopWatch.Elapsed; 

    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", 
     ts.Hours, ts.Minutes, ts.Seconds, 
     ts.Milliseconds/10); 
    Console.WriteLine("RunTime " + elapsedTime); 
} 
+2

用ts.ToString(「hh:mm: ss.ff「)'或'ts.ToString(」G「)'? – Oliver 2012-04-11 13:53:38

11

您應該使用秒錶類的定時功能。

嘗試以下操作:

private int counter = 0; 

// setup stopwatch and begin timing 
var timer = System.Diagnostics.Stopwatch.StartNew(); 

Result result = new Result(); 
result = new GeneticAlgorithms().TabuSearch(parametersTabu, functia); 

// stop timer and get elapsed time 
timer.Stop(); 
var elapsed = timer.Elapsed; 

// display result time 
MessageBox.Show(elapsed.ToString("mm':'ss':'fff")); 
4

也許,你可以寫一個這樣的方法:

public static void Time(Action action) 
{ 
    Stopwatch st = new Stopwatch(); 
    st.Start(); 
    action(); 
    st.Stop(); 
    Trace.WriteLine("Duration:" + st.Elapsed.ToString("mm\\:ss\\.ff")); 
} 

而且使用這樣的:

Time(()=> 
{ 
CallOfTheMethodIWantToMeasure(); 
}); 
7

Visual Studio 2015,2017年專業企業有診斷工具。如果你有你的函數結束一個斷點,它會顯示爲顯示圖像中的活動選項卡下的時間和持續時間:

Enter image description here

你可以看到這篇文章Diagnostic Tools debugger window in Visual Studio 2015更多細節。

PS;到目前爲止只有Xamarin形式,跨平臺項目不支持這個功能。我希望微軟也爲xamarin表單項目帶來這個強大的功能。

+0

這已經很長一段時間 – goodies4uall 2016-05-03 16:17:56

1

我審查並同意所有建議。但是想要共享一個執行時間記錄器的通用實現,我們不想多次實現Stopwatch邏輯,但仍想測量多個方法的執行時間。

不以通用方式實現記錄器的主要原因是 - 方法執行在stopwatch.Start()和stopwatch.Stop()之間,我們也可能需要在執行後進行進一步處理的方法結果。

所以爲了解決這個問題,我創建了下面的示例實現,其中執行時間單獨記錄而不與實際方法流程混合。

public static class Helper 
{ 
    public static T Time<T>(Func<T> method, ILogger log) 
    { 
     var stopwatch = new Stopwatch(); 
     stopwatch.Start(); 
     var result = method(); 
     stopwatch.Stop(); 
     log.Info(string.Format("Time Taken For Execution is:{0}", stopwatch.Elapsed.TotalMilliseconds)); 
     return result; 
    } 
} 

public class Arithmatic 
{ 
    private ILogger _log; 
    public Arithmatic(ILogger log)//Inject Dependency 
    { 
     _log = log; 
    } 

    public void Calculate(int a, int b) 
    { 
     try 
     { 
      Console.WriteLine(Helper.Time(() => AddNumber(a, b), _log));//Return the result and do execution time logging 
      Console.WriteLine(Helper.Time(() => SubtractNumber(a, b), _log));//Return the result and do execution time logging 
     } 
     catch (Exception ex) 
     { 
      _log.Error(ex.Message, ex); 
     } 
    } 

    private string AddNumber(int a, int b) 
    { 
     return "Sum is:" + (a + b); 
    } 

    private string SubtractNumber(int a, int b) 
    { 
     return "Subtraction is:" + (a - b); 
    } 
} 

public class Log : ILogger 
{ 
    public void Info(string message) 
    { 
     Console.WriteLine(message); 
    } 

    public void Error(string message, Exception ex) 
    { 
     Console.WriteLine("Error Message:" + message, "Stacktrace:" + ex.StackTrace); 
    } 
} 

public interface ILogger 
{ 
    void Info(string message); 
    void Error(string message, Exception ex); 
} 

調用部分:

static void Main() 
{ 
    ILogger log = new Log(); 
    Arithmatic obj = new Arithmatic(log); 
    obj.Calculate(10, 3); 
    Console.ReadLine(); 
} 
+0

有趣的想法。感謝發佈。 – 2016-09-02 06:13:32

+0

你不覺得代碼中包含太多無關的信息,我相信只有幫助者方法及其在一行中的用法已經足夠了 – mkb 2017-09-15 14:17:32

+0

有些擴展我同意,但是如果想在更廣泛/企業級別使用這個概念,信息並不無關聯那麼他必須考慮所有這些信息,比如記錄器等等。所以我剛纔提到了詳細的實施方式。 – 2017-09-15 17:30:20

1

記錄時當前步驟開始處理

DateTime dtStart = DateTime.Now; 

//Calculate the total number of milliseconds request took (Timespan = to represent the time interval)-> current - started time stamp ... 
//TotalMilliseconds -->Gets the value of the current TimeSpan structure expressed in whole and fractional milliseconds. 
// to measure how long a function is running 
var result=((TimeSpan)(DateTime.Now - dtStart)).TotalMilliseconds.ToString("#,##0.00") + "ms";