使用RDTSC指令的CPU时间循环秒表类

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;
}

结果显示在对话框中

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值