码迷,mamicode.com
首页 > 系统相关 > 详细

高精度 高分辨率 计时函数 Linux

时间:2015-09-30 16:24:56      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:

在优化程序过程中,经常性的要统计时间,尤其是科学计算程序,只有在理解每一个部分占用的时间的基础上,才能做进一步的优化和分析。

但是常规的时间函数精度比较低,对某个函数执行时间的测量可能得到的结果为零,但是循环次数很多的情况下又会占用很大的时间,此处你可能会说可以将其他的地方屏蔽掉来单纯测量某一个函数执行多次的时间,但是这样编译器可能会做一些优化,直接或间接地影响测量的准确性。

Linux 环境下 POSIX提供了一个纳秒(ns=10^-9s)级别的测量函数,这样就不会出现因为某个函数的执行时间过小而没法测量的情况。

#include <stdio.h>
#include <time.h>

/* gcc xx.c -lrt */
struct timespec diff(struct timespec tic, struct timespec toc); struct timespec accu(struct timespec total,struct timespec cur); int main() { struct timespec tic,toc,dur; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tic); clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &toc); dur=diff(tic,toc); printf("%d:%d\n",dur.tv_sec,dur.tv_nsec); return 0; } struct timespec diff(struct timespec tic, struct timespec toc) { struct timespec temp; if ((toc.tv_nsec-tic.tv_nsec)<0) { temp.tv_sec = toc.tv_sec-tic.tv_sec-1; temp.tv_nsec = 1000000000+toc.tv_nsec-tic.tv_nsec; } else { temp.tv_sec = toc.tv_sec-tic.tv_sec; temp.tv_nsec = toc.tv_nsec-tic.tv_nsec; } return temp; } struct timespec accu(struct timespec total,struct timespec cur) { struct timespec ret; if ( total.tv_nsec+cur.tv_nsec>=1000000000 ) { ret.tv_sec =total.tv_sec+cur.tv_sec+1; ret.tv_nsec=total.tv_nsec+cur.tv_nsec-1000000000; } else { ret.tv_sec =total.tv_sec+cur.tv_sec; ret.tv_nsec=total.tv_nsec+cur.tv_nsec; } return ret; }

用 clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tic); 函数便可以很精确的测量某段代码的执行时间(当然此段代码是同步代码,也就是阻塞的)。

同时提供的diff函数可以统计两个测量点之间的时间差,tv_sec 表示整秒数tv_nsec表示以ns为单位的小数部分。也就是说总时间为 tv_sec+tv_nsec/1E9 秒。

 

当然fftw中的测量函数针对linux用的是RDTSC 这个需要除以CPU频率才能得到具体的秒单位。相对而言在Linux下clock_gettime更为方便快捷。

 

附上某次我做实验的结果,通过这个测量可以看到程序中的核心耗时部分。

技术分享

 

参考:

http://www.guyrutenberg.com/2007/09/22/profiling-code-using-clock_gettime/

http://man7.org/linux/man-pages/man2/clock_gettime.2.html

https://aufather.wordpress.com/2010/09/08/high-performance-time-measuremen-in-linux/

 

高精度 高分辨率 计时函数 Linux

标签:

原文地址:http://www.cnblogs.com/reedlau/p/4849080.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!