看下面的代码
// 使用 StopWatch 进行测量
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
++i;
}
sw.Stop();
Console.WriteLine(sw.Elapsed);
// 使用 DateTime 进行测量
DateTime d = DateTime.Now;
for (int i = 0; i < 1000; i++)
{
++i;
}
Console.WriteLine(DateTime.Now - d);
输出
00:00:00.0000217
00:00:00
测量精度一目了然。
-----可爱的分割线-------------
StopWatch 几个关键属性和方法。
Elapsed :获取当前实例测量得出的总运行时间。在测试期间或者结束时均可获取。
IsRunning : 获取一个指示 Stopwatch 计时器是否在运行的值。
Start : 开始或继续测量某个时间间隔的运行时间。 多次调用 Start 前,需要使用 Reset 重置,否则会累加多次测量结果。
Stop : 停止测量某个时间间隔的运行时间。
Reset : 停止时间间隔测量,并将运行时间重置为零。
另:
int s = Environment.TickCount;
// do some works
int e = Environment.TickCount;
int span = e - s;