计时器找经过的时间在C中的函数调用

计时器找经过的时间在C中的函数调用

本文介绍了计时器找经过的时间在C中的函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要计算在C函数调用期间经过的时间,以1纳秒的precision。

I want to calculate time elapsed during a function call in C, to the precision of 1 nanosecond.

有没有在C语言定时器功能做呢?

Is there a timer function available in C to do it?

如果有,请提供样本code-片段。

If yes please provide a sample code-snippet.

伪code

Timer.Start()
foo();
Timer.Stop()
Display time elapsed in execution of foo()



环境的详细信息: - 使用gcc编译器3.4在RHEL机器上

Environment details: - using gcc 3.4 compiler on a RHEL machine

推荐答案

请问你用什么样的处理器?如果您使用的是x86处理器,你可以看看时间戳计数器( TSC )。这code片断:

May I ask what kind of processor you're using? If you're using an x86 processor, you can look at the time stamp counter (tsc). This code snippet:

#define rdtsc(low,high) \
     __asm__ __volatile__("rdtsc" : "=a" (low), "=d" (high))

将会把CPU已经在分别为(预计2 <$运行的周期数C $ C>长 S;可以将结果保存在得到long long int )如下:

will put the number of cycles the CPU has run in low and high respectively (it expects 2 longs; you can store the result in a long long int) as follows:

inline void getcycles (long long int * cycles)
{
  unsigned long low;
  long high;
  rdtsc(low,high);
  *cycles = high;
  *cycles <<= 32;
  *cycles |= low;
}

请注意,此返回你的CPU已经执行周期数。你需要让你的CPU速度,然后弄清楚每纳秒多少个周期,以获得经过纳秒数。

Note that this returns the number of cycles your CPU has performed. You'll need to get your CPU speed and then figure out how many cycles per ns in order to get the number of ns elapsed.

要做到上面,我已经解析了CPU MHz的串出的/ proc内/ cpuinfo ,而且它转换为十进制。在此之后,它只是一个位数学的,记住为1MHz =每秒100万次,并有1条十亿纳秒/秒。

To do the above, I've parsed the "cpu MHz" string out of /proc/cpuinfo, and converted it to a decimal. After that, it's just a bit of math, and remember that 1MHz = 1,000,000 cycles per second, and that there are 1 billion ns / sec.

这篇关于计时器找经过的时间在C中的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:52