Windows提供了如下的高精度性能函数:
BOOL QueryPerformanceFrequency(LARGE_INTEGER* pliFrequency);
BOOL QueryPerformanceCounter(LARGER_INTEGER* pliCount);
这些函数假设正在执行的线程不会被抢占,但是大多数高精度性能分析都是针对生命期限很短的代码块。可以使用下面的封装C++类来测试时间:
// QueryPerformance.h
#ifndef _QUERY_PERFORMANCE_H
#define _QUERY_PERFORMANCE_H
#include <Windows.h>
class CStopwatch
{
public:
CStopwatch();
void Start();
__int64 Now() const;
__int64 NowInMicro() const;
private:
LARGE_INTEGER m_liPerfFreq; // Counts per second
LARGE_INTEGER m_liPerfStart; // starting count
};
#endif
// QueryPerformance.cpp
#include "QueryPerformance.h"
CStopwatch::CStopwatch()
{
QueryPerformanceFrequency(&m_liPerfFreq);
Start();
}
void CStopwatch::Start()
{
QueryPerformanceCounter(&m_liPerfStart);
}
__int64 CStopwatch::Now() const
{
LARGE_INTEGER liPerfNow;
QueryPerformanceCounter(&liPerfNow);
return (((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000) / m_liPerfFreq.QuadPart);
}
__int64 CStopwatch::NowInMicro() const
{
LARGE_INTEGER liPerfNow;
QueryPerformanceCounter(&liPerfNow);
return (((liPerfNow.QuadPart - m_liPerfStart.QuadPart) * 1000000) / m_liPerfFreq.QuadPart);
}
使用方法:
// 创建一个计时器对象 -- stopwatch (默认为当前的时间)
CStopwatch stopwatch;
// 需要测试的代码
...........
...........
...........
// 获取到现在消耗的时间
__int64 qwElapsedTime = stopwatch.Now(); // 单位为:毫秒(ms)