Intel Pentium系列CPU不被C/C++访问的特性中,有一条指令对程序员来说非常重要,就是RDTSC(Read Time Stamp Counter,读取时间计数器)指令,它以64位无符号整数形式,通过EDX和EAX32位普通寄存器对,返回自CPU引导后时针走过的圈数。要使用这个指令,插入其机器代码格式0X0F、0x31。下面是类的实现:
//timer.h
#pragma once
inline unsigned __int64 GetCycleCount(void)
{
_asm _emit 0x0F
_asm _emit 0x31
}
class KTimer
{
unsigned __int64 m_startcycle;
public:
unsigned __int64 m_overhead;
KTimer(void)
{
m_overhead = 0;
Start();
m_overhead = Stop();
}
void Start(void)
{
m_startcycle = GetCycleCount();
}
unsigned __int64 Stop(void)
{
return (GetCycleCount() - m_startcycle - m_overhead);
}
};
下面是一个示例程序,用KTimer来计算CPU时钟速度和创建一个纯画刷所需的时间:
// TestClock.cpp : Defines the entry point for the application.
//
#define STRICT
#define WIN32_LEAN_AND_MEAN
#include "StdAfx.h"
#include <tchar.h>
#include "Timer.h"
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
KTimer timer;
TCHAR mess[128];
timer.Start();
Sleep(1000);
unsigned cpucpeed10 = (unsigned)(timer.Stop()/100000);
timer.Start();
CreateSolidBrush(RGB(0xAA,0xAA,0xAA));
unsigned time = (unsigned)timer.Stop();
wsprintf(mess,_T("CPU speed %d.%d mhz/nKTimer overhead %d clock cycles/n CreateSolidBrush %d clock cycles %d ns"),
cpucpeed10/10,cpucpeed10%10,(unsigned)timer.m_overhead,
time,time*10000/cpucpeed10);
MessageBox(NULL,mess,_T("How fast is GDI?"),MB_OK);
return 0;
}
结果显示在对话框中