您的位置:首页 > 其它

使用 performance-counter 计算时间间隔

2013-09-03 08:21 399 查看
还是作为上篇文章的补充的补充,因为没有给出两种方法消耗时间的比较所以就另起一篇把测试数据补充完整,顺便简单介绍如何使用 performance-counter 来计算时间,如果已经了解的朋友就不必浪费喝茶的时间的了。


补充部分

上篇链接:http://blog.csdn.net/funte/article/details/10940683

首先放出上篇的测试结果补充:

测试图像1两种方法的消耗时间对比:



测试图像1两种方法的消耗时间对比:



测试图像1两种方法的消耗时间对比:



如何使用 performance-counter

使用performance-counter计算时间和 GetSystemTime 之类的不同,首先需要得 performance-counter 的频率f,而这个计数器频率是固定的,所以计算一次就好,然后得到 开始时刻(之所以用时刻这个词是因为我没有想到合适的词,感觉就有点像老和尚敲木鱼,咚~咚~咚~)Ta,和结束时刻Tb, 消耗的时间(ms) = 1000.0f×(Tb - Ta)/f

首先介绍如何使用 performance-counter 是需要用到的两条函数:


本图来自MSDN

这个函数用来返回计数器频率,每秒的频率,接收参数需要使用一个64位整数。


本图来自MSDN

这个函数用来返回当前时间刻度。

微软没有提供 performance-counter的封装类,所以就自己定义一个结构体如下:

typedef struct _timecount{
	__int64 frequency;			// 频率
	__int64 _starttime;			// 开始时刻
	__int64 _endtime;			// 结束时刻
	float elpased;				// 流逝的的时间
}timecount;


代码

下面是整篇console的工程代码,可以跑的完整程序:

part1: stdafx.h

。。略

part2: High-Resolution Timer.cpp

// High-Resolution Timer.cpp : 定义控制台应用程序的入口点。
//
// 使用 high-resolution performance counter 计算时间间隔

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

#pragma comment(lib, "Winmm.lib")

typedef struct _timecount{ __int64 frequency; // 频率 __int64 _starttime; // 开始时刻 __int64 _endtime; // 结束时刻 float elpased; // 流逝的的时间 }timecount;

char *poem =
"《得意人生》-特雷西.K.史密斯\n\
\t有些人提及钱时,\n\
\t就像在谈某个神秘情人。\n\
\t说那个去买牛奶便一去不回的小美人,\n\
\t倒是勾起了我对往昔的几份眷恋。\n\
\t那些年总是饥肠辘辘,\n\
\t赶在上班的路上,\n\
\t以咖啡和面包充饥。\n\
\t如今却像一个背井离乡的村妇正在水上漂游,\n\
\t和别人一样,\n\
\t挥洒着一两夜觥筹交错的日子。\n";

timecount tc;
void happy7Xi();
int _tmain(int argc, _TCHAR* argv[])
{
if( QueryPerformanceFrequency( (LARGE_INTEGER*)&tc.frequency ) )
{
QueryPerformanceCounter( (LARGE_INTEGER*)&tc._starttime );
happy7Xi();
QueryPerformanceCounter( (LARGE_INTEGER*)&tc._endtime );
tc.elpased = (float)(tc._endtime - tc._starttime)/(float)tc.frequency;
cout<<tc.elpased<<"s"<<endl;

}else{
cout<<"no support for high-resolution performance counter \n"<<endl;
system("pause");
return 0;
}

getchar();
return 0;
}

void happy7Xi()
{
cout<<poem<<endl;
}
运行结果:



本篇结束。

如有任何错误或者更好的方法或建议,欢迎指正


1562165834@qq.com
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: