//执行实际的测试
timer.Start();
for(int i =0; i < 1000; i++)
quantity += i;//防止被JIT优化
timer.Stop();
//输出结果
Console.WriteLine("Counting to 1000:");
Console.WriteLine(" "+timer.ToString());
Console.WriteLine("##########################################");
}
Console.WriteLine("\nquantity is "+quantity);
}
}
/// <summary>
/// 封装的计时器类
/// </summary>
public class IntervalTimer
{
[DllImport("kernel32.dll")]
static extern private int QueryPerformanceCounter(out long count);
[DllImport("kernel32.dll")]
static extern private int QueryPerformanceFrequency(out long count);
//表示计时器是否已经启动或者停止的枚举
public enum TimerState{NotStarted,Stopped,Started}
private TimerState state;
private long ticksAtStart; //tick count when Start() called
private long intervalTicks; //no. of ticks elapsed until Stop() called
private static long frequency; //存储计时器频率的信息,每秒包含的时间片数量
private static long decimalPlaces;//在输出计时信息时使用,存储精度的值
private static string formatString; //存储格式化字符串
private static bool initialized=false;
private static long CurrentTicks
{
get
{
long t;
QueryPerformanceCounter(out t);
return t;
}
}
public IntervalTimer()
{
if(!initialized)
{
QueryPerformanceFrequency(out frequency);//确定频率
decimalPlaces = (int)Math.Log10(frequency);
formatString = String.Format("Interval:{{0:F{0}}} seconds ({{1}} ticks)",
decimalPlaces);
initialized = true;
}
state = TimerState.NotStarted;
}
public void Start()
{
state = TimerState.Started;
ticksAtStart = CurrentTicks;
}
public void Stop()
{
intervalTicks = CurrentTicks - ticksAtStart;
state = TimerState.Stopped;
}
// 计算调用Start()和Stop()分别需要耗费多少时间片
public float GetSeconds()
{
if(state != TimerState.Stopped)
throw new TimerNotStoppedException();
return (float)intervalTicks/ (float)frequency;
}
//自定义的异常
public class TimerNotStoppedException:ApplicationException
{
public TimerNotStoppedException()
:base("Timer is either still running or has not been started")
{
}
}
}
这主要看你对于精度的要求了,一般10ms到1s的时间间隔用简单的方法很难准确得到。因为一般系统提供的基本计时方式,就是基于timer(低频中断计时器)和counter(时钟周期计数器)在这个范围都工作的不是很好。如你有兴趣,可以看看《Computer Systems A Programmer's Perspective》Chapter 9,很有帮助