2016-12-21 128 views
0

我的程序的一部分多次調用某種方法。方法調用之間的時間差

該方法如何跟蹤每次調用之間的時間?

我想使用一些全局變量:

var lastTime = ?; 
var currentTime = ?; 
var elapsedTime = ?; 

public DoSomething() 
{ 
    currentTime = TimeRightNowInSeconds; 
    elapsedTime = currentTime - lastTime; 
    // do stuff with elapsedTime... 
    lastTime = TimeRightNowInSeconds; 
} 

,但我不知道我是怎麼衡量的秒數。

+2

呃,'秒錶'? –

+0

https://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx – ViVi

+1

可能的重複[在C#中測量執行時間](http://stackoverflow.com/questions/3903222/measure-execution-time-in-c-sharp) – Backs

回答

0

考慮使用DateTimeTimeSpan(小心使用DateTime.UtcNow避免日光節約邊界問題)

例如

var start = DateTime.UtcNow; 
... 
var end = DateTime.UtcNow; 
var elapsed = end.Subtract(start); //elapsed is a TimeSpan 
var elapsedSeconds = elsapsed.Seconds; 

這也可以用做Stopwatch(這是比較準確的,並從問題夏令界限並不吃虧)

var stopwatch = Stopwatch.StartNew(); 
... 
stopwatch.Stop(); 
var elapsedSeconds = stopwatch.Elapsed.Seconds; //stopwatch.Elapsed is a TimeSpan 
+0

什麼類型是elapsedSeconds?如果不是int,我如何使它成爲int? – theonlygusti

+0

是的,這是一個int。 – Stephan

0

在這個解決方案,您將看到如何讓時間方法之間呼叫 Link

class Program 
{ 
    static Stopwatch _stopWatch = new Stopwatch(); // stopwatch 
    static long _lastTime; // time in milliseconds 


    static void Main(string[] args) 
    { 
    /* _lastTime will be 0 when first call ElapsedTime(). */ 
    ElapsedTime(); 

    /* Hold the current thread for 1000 milliseconds */ 
    Thread.Sleep(1000); 

    /* _lastTime will be 1000 when second call ElapsedTime(). */ 
    ElapsedTime(); 
    Thread.Sleep(2000); 

    /* _lastTime will be 3000 when third call ElapsedTime(). */ 
    ElapsedTime(); 

    /* Thread.Sleep() is to simulate time between the calls of the method */ 
    /* _lastTime is in milliseconds*/ 
    } 


    public static void ElapsedTime() 
    { 
    // check if stopwatch already started once 
    if (_stopWatch .IsRunning) 
    { 
     /* get the totlal elapsed milliseconds */ 
     _lastTime += _stopWatch .ElapsedMilliseconds; 
     /* Restart stopwatch */ 
     _stopWatch .Restart(); 
     } 
     else 
     { 
     _stopWatch .Start(); 
     } 

    Console.WriteLine(_lastTime); 
    } 
}