欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Windows实现精确计时

程序员文章站 2024-01-24 09:03:34
...
//
//QueryPerformanceCounter()这个函数返回高精确度性能计数器的当前计数值
//QueryPerformanceFrequency()返回机器内部定时器的时钟频率,每秒嘀哒声的个数.
//两次计数值之差除以时钟频率就是两次的间隔时间,单位是秒
//

#include <iostream>
#include<stdio.h>
#include<Windows.h>

using namespace std;

int main()
{
	LARGE_INTEGER nFreq;
	LARGE_INTEGER nBeginTime;
	LARGE_INTEGER nEndTime;

	QueryPerformanceFrequency(&nFreq);

	QueryPerformanceCounter(&nBeginTime);

	for (int i = 0;i < 1000;++i)
	{
		printf("%d\n",i);
	}

	QueryPerformanceCounter(&nEndTime);

	int continueTime = (double)(nEndTime.QuadPart - nBeginTime.QuadPart)*1000 / nFreq.QuadPart;  //获得对应的时间值,单位为秒

	printf( "time cost is %d ms.", continueTime);
	system("pause");
	return 0;
}