在 C# 裡,還真的有碼錶類別可使用哩!正巧也叫「Stopwatch」。功能也很簡單,大概常會用到的,應該只有啟動(Start)、暫停(Stop)、清除(Reset) 這三項。
以簡單例子來說明:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace ElapsedTime
{
class Program
{
static void Main(string[] args)
{
Stopwatch stop = new Stopwatch();
//啟動計時
stop.Start();
//使用 Thread.Sleep 模擬耗時的程式流程
Thread.Sleep(10000);
//停止計時
stop.Stop();
//取得耗時數據
TimeSpan ts = stop.Elapsed;
//列印耗時結果
Console.WriteLine(string.Format("{0:00}:{1:00}:{2:00}:{3:00}",
ts.Hours,ts.Minutes,ts.Seconds,ts.Milliseconds/10));
Console.ReadKey();
}
}
}
日後,如果要比較程式效能時,就可以透過這碼錶取得精確的數據。參考:Stopwatch 類別
沒有留言:
張貼留言