因为经常用到SetEvent和WaitForSingleObject函数组合,来实现事件触发,觉得非常好用,但一直很好奇,这些函数的执行效率如何?或者说,当执行了一个SetEvent触发,大概需要多长时间,WaitForSingleObject才会响应,因为这些数据在实时性操作时是需要明确回答出的。
(2015-01-17补充:测量延时,还可以使用高性能计数器函数QueryPerformanceFrequency、QueryPerformanceCounter。使用说明见文档:http://blog.csdn.net/dijkstar/article/details/23092747)
测试程序:
// Test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Test.h"
#include <afxmt.h>
#include <Mmsystem.h>
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/
// The one and only application object
CWinApp theApp;
using namespace std;
//链接库
#pragma comment(lib, "Winmm.lib")
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
//
// 使用MFC的事件类,才能等待函数循环转起来
//
CEvent evt;
evt.SetEvent(); //默认的是“触发完毕自动清除,需要再次手动触发”
//
// 创建一个高精度计时器
//
::timeBeginPeriod(1);
Sleep(100);
DWORD s = timeGetTime();//开始时间(毫秒级)
//
// 循环10个百万
//
for (int i=0; i<10000000; i++)
{
WaitForSingleObject((HANDLE)evt, INFINITE);
//........
evt.SetEvent(); //如果将该句注释,那么循环就不转了
}
//
// 结束
//
DWORD e = ::timeGetTime();//结束时间(毫秒级)
printf("%d\n", e-s);//
}
return nRetCode;
}
① MFC类的CEvent的类成员函数SetEvent只是薄薄的包装了一层Win32的 ::SetEvent函数,也就是两者基本相同;
② 多媒体库下的计时函数,计时精度到毫秒级,是可信的。
在CPU:i5-3210 2.5G+4G内存+WIN7的机器上,上述结果为5443ms,也就是每一次“等待”和“触发”的执行时间为0.54ns左右。也就是这些函数的执行效率相当的高。即因这些函数造成的延时在纳秒级,不必考虑。