我使用了Windows API GetLocalTime(SYSTEMTIME *)来获取函数调用之前和之后的当前系统时间,我想测量它的时间.
但这有缺点,它的最低分辨率只有1毫秒.没有什么比这更好了.所以我不能在微秒内获得任何时间粒度.
我知道time()给出了自纪元时间以来经过的时间,也有1毫秒(无微秒)的分辨率
1.)是否有任何其他Windows API提供微秒的时间,我可以用来测量我的功能消耗的时间?
-广告
解决方法
QueryPerformanceCounter和QueryPerformanceFrequency
QueryPerformanceCounter将返回一个“性能计数器”,它实际上是一个cpu管理的64位计数器,从计算机开机时开始从0开始递增.该计数器的频率由QueryPerformanceFrequency返回.要以秒为单位获取时间参考,请按性能频率划分性能计数器.在德尔福:
function QueryPerfCounterAsUS: int64; begin if QueryPerformanceCounter(Result) and QueryPerformanceFrequency(perfFreq) then Result := Round(Result / perfFreq * 1000000); else Result := 0; end;
在多处理器平台上,无论线程当前运行的cpu如何,QueryPerformanceCounter都应返回一致的结果.但是,偶尔会出现问题,通常是由硬件芯片或BIOS中的错误引起的.通常,补丁由主板制造商提供. MSDN的两个例子:
> Programs that use the QueryPerformanceCounter function may perform poorly in Windows Server 2003 and in Windows XP
> Performance counter value may unexpectedly leap forward
QueryPerformanceCounter的另一个问题是它很慢.
RDTSC指令
如果可以将代码限制为一个cpu(SetThreadAffinity),则可以使用RDTSC汇编程序指令直接从处理器查询性能计数器.
function cpuGetTick: int64; asm dw 310Fh // rdtsc end;
RDTSC结果以与QueryPerformanceCounter相同的频率递增.将它除以QueryPerformanceFrequency,以秒为单位获取时间.
QueryPerformanceCounter比RDTSC慢得多,因为它必须考虑多个cpu和具有可变频率的cpu.从Raymon Chen’s blog:
(QueryPerformanceCounter) counts elapsed time. It has to,since its value is
governed by the QueryPerformanceFrequency function,which returns a number
specifying the number of units per second,and the frequency is spec’d as not
changing while the system is running.For cpus that can run at variable speed,this means that the HAL cannot
use an instruction like RDTSC,since that does not correlate with elapsed time.
timeGetTime
TimeGetTime属于Win32多媒体Win32功能.它以毫秒为单位返回时间,分辨率为1 ms,至少在现代硬件上.如果在开始测量时间之前运行timeBeginPeriod(1)并且在完成时测量timeEndPeriod(1),则不会受到伤害.
GetLocalTime和GetSystemTime
在Vista之前,GetLocalTime和GetSystemTime都以毫秒精度返回当前时间,但它们不精确到毫秒.它们的准确度通常在10到55毫秒的范围内. (Precision is not the same as accuracy)在Vista上,GetLocalTime和GetSystemTime都以1 ms的分辨率工作.