代码运行的绝对时间和机器的许多因素有关,如下所列就是一些常见的因素。
机器硬件配置和特性
机器的系统种类
机器软件包安装情况
机器进程序调度情况
代码编译优化情况和编译器种类
我简单整理了一下,利用win32 api函数,QueryPerformanceCounter 来达到精确计时的目地。构造了一个测试代码性能的类,自已用了感觉还不错,想到别人也可能用到计算程序性能的问题,就发出来共享一下,如果有什么意见或是bug,可以联系我。
/* * KBestMeasure.h * A class to test code performance using k best method * Contributors: * Created by saturnman <saturnman AT 163.com> * THIS SOFTWARE IS NOT COPYRIGHTED * * This source code is offered for use in the public domain. You may * use, modify or distribute it freely. * * This code is distributed in the hope that it will be useful but * WITHOUT ANY WARRANTY. ALL WARRANTIES, EXPRESS OR IMPLIED ARE HEREBY * DISCLAIMED. This includes but is not limited to warranties of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ #ifndef MEASURE_H_ #define MEASURE_H_ #include <iostream> #include <cstdlib> #include <vector> #include <cmath> #include <iterator> #include <algorithm> #include <windows.h> #include <functional> #include <numeric> using namespace std; class Measure { public: enum STATE{before_init_s,run_s,stop_s}; public: Measure() { this->m_state = before_init_s; } void start() { QueryPerformanceCounter(&(this->m_start_tick)); this->m_state = run_s; } void stop() { if(this->m_state != run_s) { cerr<<"Measure in wrong state."<<endl; exit(1); } QueryPerformanceCounter(&(this->m_end_tick)); this->m_state = stop_s; } int get_result() { int result; if(this->m_state != stop_s) { cerr<<"Measure in wrong state."<<endl; exit(1); } else { result = m_end_tick.QuadPart-m_start_tick.QuadPart; } return result; } private: LARGE_INTEGER m_start_tick; LARGE_INTEGER m_end_tick; STATE m_state; }; |