2016-12-21 95 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); 
    } 
}