DateTime.Now的精度是很低,这个低的意思是,两次获取的DateTime.Now的Ticks的差,只是一个较大数的整数倍。例如在我的机器上,这个差最小是10.114ms。所以,如果我用DateTime.Now来计算时间差,那么就无法精确到10ms以内。
后来发现ASP.NET的TRACE的精度很高,用Reflector看它的实现,发现了它是使用这两个方法的:
参考
MSDN:How To: Time Managed Code Using QueryPerformanceCounter and QueryPerformanceFrequency我自己加了一个方法GetRunTime,用以获取运行时间(毫秒或秒),代码如下:
// QueryPerfCounter.cs
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace TSXMLOVE
{
public class QueryPerfCounter
{
[DllImport("KERNEL32")]
private static extern bool QueryPerformanceCounter(
out long lpPerformanceCount);
[DllImport("Kernel32.dll")]
private static extern bool QueryPerformanceFrequency(out long lpFrequency);
private long start;
private long stop;
private long frequency;
Decimal multiplier = new Decimal(1.0e9);
public QueryPerfCounter()
{
if (QueryPerformanceFrequency(out frequency) == false)
{
// Frequency not supported
throw new Win32Exception();
}
}
public void Start()
{
QueryPerformanceCounter(out start);
}
public void Stop()
{
QueryPerformanceCounter(out stop);
}
public double Duration(int iterations)
{
return ((((double)(stop - start) * (double)multiplier) / (double)frequency) / iterations);
}
public double GetRunTime(TimeType timeType) {
return (this.Duration(1) / (int)timeType);
}
public enum TimeType {
Seconds = 1000000000
, MilliSeconds = 1000000
}
}
}
在ASP.NET的应用
TSXMLOVE.QueryPerfCounter timer=new TSXMLOVE.QueryPerfCounter();
timer.Start();
需要计算运行时间代码...
timer.Stop();
double useTime=timer.GetRunTime(TimeType.Seconds);
这样就可以达到获取到“需要计算运行时间代码...”所运行的精确时间了。