2012-04-21 33 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();