2012-04-21 271 views
2

当我开始某个过程时,我记录DateTime.Now并记住它作为StartTime。绝对时间测量

在后面的过程中,我从DateTime.Now减去StartTime以计算这两者之间的时间 - 在开始时间和当前时间之间。

现在,问题是这种方法并不总是准确的 - 在过程中,时间可能会被使用时间服务器的窗口或用户手动更改。

是否还有其他一些方法来测量所描述的时间,即使在此期间窗口时间会发生变化,它也将始终正常工作?

+0

太好了,那正是我想要的 – Dusan 2012-04-21 12:35:14

回答

1

使用秒表。

var a = Stopwatch.StartNew(); // Initializes and starts running 
var b = new Stopwatch(); // Initializes and doesn't start running 

var c = a.Elapsed; // TimeSpan 

a.Stop(); 
a.Start(); 
a.Reset(); 

秒表就像一个手表本身,所以它不指望电脑的时钟。 只需在开始时启动一个,然后检查Elapsed以查看已经过了多少时间。

1

你可以使用这个:Get time of Code Execution Using StopWatch

Stopwatch stopWatch = new Stopwatch(); 
stopWatch.Start(); 
//instead of this there is line of code that you are going to execute 
Thread.Sleep(10000); 
stopWatch.Stop(); 
// Get the elapsed time as a TimeSpan value. 
TimeSpan ts = stopWatch.Elapsed; 
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", 
ts.Hours, ts.Minutes, ts.Seconds, 
ts.Milliseconds/10); 
Console.WriteLine(elapsedTime); 
Console.ReadLine();