用于在C++代码中获取和显示调用函数或执行代码片段消耗的时间。
主要借助<time.h>
,原理基于以下的代码:
1 2 3 4 5 6 7 8 9
| #include <time.h>
clock_t start = clock();
clock_t end = clock(); float dur = (double)(end-start)/CLOCKS_PER_SEC; printf("use time = %f",dur);
|
具体使用时有两种方案:
局部变量方法
函数或代码片段开始时声明局部变量,函数或代码片段结束时自动调用析构:
声明类AutoTimer
如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #pragma once #include <string> #include <time.h> using std::string;
class AutoTimer { public: AutoTimer(string& str); AutoTimer(const char* str); AutoTimer(); ~AutoTimer(); private: clock_t m_start; string m_str; };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| #include "FunctionTimer.h" #include <iostream>
using namespace FunctionTimer; using std::cout; using std::endl;
AutoTimer::AutoTimer() { m_str = ""; m_start = clock(); }
AutoTimer::AutoTimer(string& str) { m_str = str; m_start = clock(); }
AutoTimer::AutoTimer(const char* str) { m_str = str; m_start = clock(); }
AutoTimer::~AutoTimer() { clock_t end = clock(); float dur = (double)(end - m_start)/CLOCKS_PER_SEC; cout << m_str << " : " << dur << "s" << endl; }
|
使用方法:
1 2 3 4 5 6 7 8 9 10
| void test() { AutoTimer at(__func__); int sum = 0; for(int i = 0 ; i < 1000000000 ; i++) { sum++; } }
|
使用宏来标记起止
定义宏如下:
1 2 3 4 5 6 7 8 9 10 11
| #define TIMER_START \ {\ clock_t ____TIMER_START_TIME;\ ____TIMER_START_TIME=clock(); #define TIMER_END \ { \ clock_t ____TIMER_END_TIME = clock();\ float dur = (double)(____TIMER_END_TIME - ____TIMER_START_TIME)/CLOCKS_PER_SEC; \ std::cout << "USE TIME : " << dur << "s" << std::endl; \ } \ }
|
使用方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| void test() { int sum = 0; int i = 0; TIMER_START; for(i = 0 ; i < 1000000000 ; ++i) { ++sum; } TIMER_END; }
|