Windows下时间测试函数


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)




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值