关于计时的一些方法

 

clock函数
   C++中的计时函数是clock(),而与其相关的数据类型是clock_t(头文件是time.h)。函数定义原型为:clock_t clock(void);
  这个函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数,在MSDN中称之为挂钟时间(wal-clock)。
  其中clock_t是用来保存时间的数据类型,在time.h文件中,我们可以找到对它的定义:
   #ifndef _CLOCK_T_DEFINED
   typedef long clock_t;
   #define _CLOCK_T_DEFINED
   #endif
  很明显,clock_t是一个长整形数。另外在time.h文件中,还定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,因此,我们就可以使用公式clock()/CLOCKS_PER_SEC来计算一个进程自身的运行时间。
  下面就上面的知识给大家举个例子帮助大家理解。
#include<iostream.h>
#include<time.h>
void main()
{
   clock_t start,finish;
   double totaltime;
   start=clock();
   ……                     
//把你的程序代码插入到这里面
   finish=clock();
   totaltime=(double)(finish-start)/CLOCKS_PER_SEC;
   cout<<"/n此程序的运行时间为"<<totaltime<<"秒!"<<endl;
}
   实际上在运行中CLOCKS_PER_SEC的大小为1000;而clock()函数的精度只能达到15ms,这样的精度不能满足程序的要求。
   
WINDOWS中的几个函数
1.  使用GetTickCount,得到当前的时间,单位是毫秒

代码示例:
DWORD startTime = GetTickCount();
//被测试的代码
DWORD totalTime = GetTickCount() - startTime;
实际在运行中GetTickCount精度只能达到15ms.
2.使用GetThreadTimes;该函数得到的时间包括两部分,内核执行的时间和用户代码的执行时间。
代码示例:

FILETIME m_ftKernelTimeStart;FILETIME m_ftKernelTimeEnd;
FILETIME m_ftUserTimeStart;
FILETIME m_ftUserTimeEnd;
GetThreadTimes(GetCurrentThread(),&m_ftDummy,&m_ftDummy,

     &m_ftKernelTimeStart,&m_ftUserTimeStart);
//被测试的代码
GetThreadTimes(GetCurrentThread(),&m_ftDummy,&m_ftDummy,

        & m_ftKernelTimeEnd,& m_ftUserTimeEnd);
使用GetThreadTimes得到的时间单位也是毫秒级别的,精度可以达到1ms;
内联汇编的方法:
#pragma once
inline unsigned __int64 GetCycleCount(
void
)
{
    _asm _emit 
0x0F 
    _asm _emit  0x31
}
class  KTimer  
{
    unsigned __int64 m_startcycle;
public
:
    unsigned __int64 m_overhead;    
// RTSC指令的运行时间 
    KTimer()
   
{
        m_overhead 
=   0
;
        Start();
        m_overhead 
=
 Stop();
    }
 
    void  Start();
    unsigned __int64 Stop();
    unsigned unsigned GetCPUSpeed();
}
;

KTimer.cpp
#include "KTimer.h"
#include <iostream>
#include <windows.h>
void KTimer::Start(){
    m_startcycle 
=
 GetCycleCount();
}
unsigned __int64 KTimer::Stop()
{
    
return GetCycleCount() - m_startcycle -
 m_overhead;
}
unsigned unsigned KTimer::GetCPUSpeed()
{
    cout 
<< "开始测试 cpu速度.." <<
 endl;
    Start();
    Sleep(
1000
);
    unsigned cputime 
=
 Stop();
    unsigned cpuspeed10 
= (unsigned)(cputime/100000
);
    cout 
<< "CPU速度 每秒:" << cputime << " clocks" <<
 endl;
    
return cpuspeed10 == 0 ? 1
 : cpuspeed10;
}


用法:

#include "stdafx.h"
#include 
<tchar.h>
#include 
<windows.h>
#include 
<iostream>
#include 
"KTimer.h"
int main(int argc, char*  argv[])
{    
    KTimer timer;
    unsigned cpuspeed10 
=
 timer.GetCPUSpeed();
    timer.Start();   
//做耗时操作
  
    unsigned time 
=
 timer.Stop();
    TCHAR mess[
128
];
    wsprintf(mess,_T(
"耗时:%d ns"), time * 10000 /
 cpuspeed10);
    cout 
<< mess <<
 endl;
    
return 0
;
}

    这个方法的精度能够达到ns级。

你可能感兴趣的:(C++,windows,汇编,测试,Class,iostream)