C++获取精确时间差

2017-11-22 15:03:54  阅读 3629 次 评论 0 条

一般情况下获取时间差可以使用GetTickCount ,此函数直接返回从开机到现在所经过的毫秒。

如果需要获取精确时间差,则可以使用QueryPerformanceCounter,此函数可以精确到 < 1us (微秒),运行环境xp以上

MSDN原文:

QueryPerformanceCounter function

Retrieves the current value of the performance counter, which is a high resolution (<1us) time stamp that can be used for time-interval measurements.

Syntax

BOOL WINAPI QueryPerformanceCounter(
  _Out_ LARGE_INTEGER *lpPerformanceCount
);

头文件:

  • Winbase.h (include Windows.h)


用法:

#include "stdafx.h"
#include <iostream>
#include <Windows.h>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
	LARGE_INTEGER freq, start, end;
	double time;
	int i=10000000;
	

	//获取时钟频率
	QueryPerformanceFrequency(&freq);

	//开始时间
	QueryPerformanceCounter(&start);
	
	//需要计时的工作	
	while (i--)
	{
		
	}

	//结束时间
	QueryPerformanceCounter(&end);
	
	time = (end.QuadPart - start.QuadPart)*1.0/freq.QuadPart;
	cout<<"耗时:"<<time<<"秒\n";
	
	//不解释
	system("pause");
	
	return 0;
}

运行输出:

耗时:0.0326518秒

请按任意键继续. . .


看这结果应该是精确到0.1微秒了




本文地址:http://bloguan.com/?id=182
版权声明:本文为原创文章,版权归 博观网 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?