標籤:轉換 參數 names htm stop net [] 計時 http
在項目中,經常要對某些方法的執行效能(消耗的時間)進行日誌記錄,有兩種方案來實現。
StopWatch
使用Stopwatch類來量度時間非常簡單。跟現實生活中的秒錶一樣,這個類的對象也能夠對計數器進行開始、停止、歸零(重設)操作,不過它可比一般的秒錶精確多了,它能夠精確到微秒(也就是百萬分之一秒)。
(以下的樣本來自於 http://www.cnblogs.com/greatandforever/archive/2008/07/23/1249185.html)
要示範Stopwatch的使用還是來段代碼吧。下面是一個控制台應用程式,它將1到100萬之間的所有整數累加:
using System;namespace StopWatchClass{ class Program { static void Main(string[] args) { long total = 0; for (int i = 1; i <= 10000000; i++) { total += i; } } }}
添加 Stopwatch 對象
Stopwatch類位於System.Diagnostics命名空間。下面是添加對象後的代碼:
using System;using System.Diagnostics;namespace StopWatchClass{ class Program { static void Main(string[] args) { Stopwatch timer = new Stopwatch(); long total = 0; for (int i = 1; i <= 10000000; i++) { total += i; } } }}
控制 Stopwatch 對象
Stopwatch提供了幾個方法用以控制Stopwatch對象。Start方法開始一個計時操作,Stop方法停止計時。此時如果第二次使用 Start方法,將繼續計時,最終的計時結果為兩次計時的累加。為避免這種情況,在第二次計時前用Reset方法將對象歸零。這三個方法都不需要參數。代碼是:
using System;using System.Diagnostics;namespace StopWatchClass{ class Program { static void Main(string[] args) { Stopwatch timer = new Stopwatch(); long total = 0; timer.Start(); for (int i = 1; i <= 10000000; i++) { total += i; } timer.Stop(); } }}
讀取 Stopwatch 結果
在結束計時後下一步就是讀取計時結果了。Stopwatch類提供了以下屬性:
- Elapsed:返回一個TimeSpan對象,表示計時時間間隔;
- ElapsedMilliseconds:返回計時經過的微秒數,精確度稍差,適合於稍長一點的計時;
- ElapsedTicks: 返回計時經過的計時器刻度(timer tick)數。計時器刻度是Stopwatch對象可能的最小量度單位。計時器刻度時間的長度由特定的電腦和作業系統確定。Stopwatch對象的 Frequency靜態欄位的值表示一秒所包含的計時器刻度數。注意它與TimeSpan的Ticks屬性所用的時間單位的區別。
應當根據計時任務的情況選擇其中的一個屬性。在我們的樣本程式中,Elapsed屬性提供了需要的精確度,用它來輸出經過的微秒數。這也是TimeSpan的最高精確度了。
下面是最終的程式碼:
using System;using System.Diagnostics;namespace StopWatchClass{ class Program { static void Main(string[] args) { Stopwatch timer = new Stopwatch(); long total = 0; timer.Start(); for (int i = 1; i <= 10000000; i++) { total += i; } timer.Stop(); decimal micro = timer.Elapsed.Ticks / 10m; Console.WriteLine("Execution time was {0:F1} microseconds.", micro); } }}
另外,使用IsRunning屬性可以查看一個Stopwatch執行個體是否正在計時,使用StartNew方法可以開始一個新的計時器。
DateTime.Now.Ticks
使用 DateTime.Now.Ticks 可以得到當前時刻的毫微秒數。在執行方法前使用變數1儲存當前毫微秒,執行方法後再用變數2儲存當前毫微秒,則相應的時間差,轉換為秒的話為:
時間間隔(秒) = (變數2 - 變數1) * 10000000d
.net 中進行消耗時間計時