如果你覺得用 DotNet 自帶的 DateTime 獲取的時間精度不夠
/// <summary>
/// 獲取時間的精度
/// </summary>
/// <param name=
/// <returns></returns>
[SuppressUnmanagedCodeSecurity]
[DllImport(
static private extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);
/// <summary>
/// 獲取時間計數
/// </summary>
/// <param name=
/// <returns></returns>
[SuppressUnmanagedCodeSecurity]
[DllImport(
static private extern bool QueryPerformanceCounter(ref long PerformanceCount);
下面是完整的封裝代碼
/// <summary>
/// 定義一個高精度的時間類
/// </summary>
public class Timer
{
#region private members
private long ticksPerSecond =
private long elapsedTime =
private long baseTime =
#endregion
#region windows API
/// <summary>
/// 獲取時間的精度
/// </summary>
/// <param name=
/// <returns></returns>
[SuppressUnmanagedCodeSecurity]
[DllImport(
static private extern bool QueryPerformanceFrequency(ref long PerformanceFrequency);
/// <summary>
/// 獲取時間計數
/// </summary>
/// <param name=
/// <returns></returns>
[SuppressUnmanagedCodeSecurity]
[DllImport(
static private extern bool QueryPerformanceCounter(ref long PerformanceCount);
#endregion
#region constructors
/// <summary>
/// new
/// </summary>
public Timer()
{
// Use QueryPerformanceFrequency to get frequency of the timer
if (!QueryPerformanceFrequency(ref ticksPerSecond))
throw new ApplicationException(
Reset();
}
#endregion
#region public methods
/// <summary>
/// 重置時間相關計數器
/// </summary>
public void Reset()
{
long time =
QueryPerformanceCounter(ref time);
baseTime = time;
elapsedTime =
}
/// <summary>
/// 獲取當前與最近一次 reset 時間差
/// </summary>
/// <returns>The time since last reset
public double GetTime()
{
long time =
QueryPerformanceCounter(ref time);
return (double)(time
}
/// <summary>
/// 獲取當前系統的時間 ticks 數
/// </summary>
/// <returns>The current time in seconds
public double GetAbsoluteTime()
{
long time =
QueryPerformanceCounter(ref time);
return (double)time / (double)ticksPerSecond;
}
/// <summary>
/// 獲取此次與上次調用此方法的兩次時間差
/// </summary>
/// <returns>The number of seconds since last call of this function
public double GetElapsedTime()
{
long time =
QueryPerformanceCounter(ref time);
double absoluteTime = (double)(time
elapsedTime = time;
return absoluteTime;
}
#endregion
}
調用代碼
Timer t = new Timer();
t
t
t
t
From:http://tw.wingwit.com/Article/program/net/201311/12714.html