c++函数执行时间

2014-11-24 11:26:16 · 作者: · 浏览: 0

计算函数的执行时间,粒度比较小,往往也能从中发现项目代码的瓶颈,及时发现问题来提升系统的性能。

c++代码时间的估算首先考虑几个时间函数:clock_gettime( ) 、gettimeofday()、_ftime()、time(),其中clock_gettime( ) 提供了纳秒级的精确度,更加准确,可以选用。

同时要考虑到往函数注入时间计算函数的时候,对于原代码要考虑易用性,尽量使用配置或者宏等形式来简单设置便能做时间统计,下面的例子使用的是加上编译宏这个方法。

例子:

#ifdef DEBUG_CODES_TIME
void timer_start(timespec *aStartTime)
{
clock_gettime(CLOCK_REALTIME, aStartTime);
}
long timer_end(timespec *aStartTime)
{
timespec endTime;
clock_gettime(CLOCK_REALTIME, &endTime);
long totalTimeMs = (endTime.tv_sec * 1000 + endTime.tv_nsec / 1000000) - (aStartTime->tv_sec * 1000 + aStartTime->tv_nsec / 1000000);
return totalTimeMs;
}
__attribute((constructor)) void timing_init()
{
;//... ... 针对具体情况进行初始化 }
#else
#define timer_start(ts)
#define timer_end(ts) -1
#endif

int main()
{
timespec ts;
timer_start(&ts);
for(int i=0; i<1000000; ++i);
long ret = timer_end(&ts);
printf("Result: %ld \n",ret);
return 0;
} $g++ test_timer.c -DDEBUG_CODES_TIME -lrt $./a.out (debug) initialize timing clock to 0.010000 seconds
Result: 4 $g++ test_timer.c $./a.out Result: -1