程序运行机时统计代码计时

  • 格式:pdf
  • 大小:75.92 KB
  • 文档页数:4

下载文档原格式

  / 4
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

{ 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 Gห้องสมุดไป่ตู้tCycleCount() - 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级。
DWORD startTime = GetTickCount();//程序计时 。。。。。。测试程序段。。。。。 DWORD totalTime = GetTickCount()-startTime; CString str; str.Format("耗费机时%u毫秒",totalTime); MessageBox(str); 关于计时的一些方法 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 = GetTtickCount() – 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

相关主题