标签:
C# 计时器
C#中一共有4中常用的计时器:
//以QueryPerformanceCounter为例:
public class Program
{
//引用Win32 API 中的 QueryPerformanceCounter() 方法
//该方法引来查询任意时刻高精度计数器的实际值
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
//引用Win32 API 中的 QueryPerformanceFrequency() 方法
//该方法返回高精度计数器每秒的计数值
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
public static void Main(string[] args)
{
long startTime, endTime;
long freq;
if (QueryPerformanceFrequency(out freq) == false)
{
//不支持高性能计时器
throw new Win32Exception();
}
Thread.Sleep(0); //让等待线程工作,此例为单线程,可省略
QueryPerformanceCounter(out startTime); //记录开始时间,精度为1ms
for (int i=0;i<10000;i++)
{
for (int j = 0; j < 10000; j++)
{
int temp = 0;
}
}
QueryPerformanceCounter(out endTime); //记录结束时间,精度为1ms
Console.WriteLine((double) (endTime - startTime)*1000/freq+"ms");
Console.ReadKey();
}
}
//Result:
//412.58911914026ms
//结果根据个人电脑的性能而有所差别
标签:
原文地址:http://www.cnblogs.com/SilentCode/p/4925307.html