我程序的一部分多次调用某种方法。
此方法如何跟踪每次调用之间的时间?
我想过使用一些全局变量:
var lastTime = ?;
var currentTime = ?;
var elapsedTime = ?;
public DoSomething()
{
currentTime = TimeRightNowInSeconds;
elapsedTime = currentTime - lastTime;
// do stuff with elapsedTime...
lastTime = TimeRightNowInSeconds;
}
但我不知道如何以秒为单位测量时间。
答案 0 :(得分:0)
考虑使用DateTime和TimeSpan(小心使用DateTime.UtcNow以避免夏令时边界问题)
e.g。
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
答案 1 :(得分: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);
}
}