计时器在 C 中的函数调用中查找经过的时间 [英] Timer to find elapsed time in a function call in C

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

问题描述

我想计算在 C 中的函数调用期间经过的时间,精确到 1 纳秒.

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?

如果是,请提供示例代码片段.

If yes please provide a sample code-snippet.

伪代码

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

<小时>

环境细节: - 在 RHEL 机器上使用 gcc 3.4 编译器

推荐答案

请问您使用的是哪种处理器?如果您使用的是 x86 处理器,您可以查看时间戳计数器 (tsc).此代码片段:

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 运行的周期数分别放在 lowhigh(它期望 2 long 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 速度,然后计算每 ns 有多少个周期才能获得经过的 ns 数.

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.

为了完成上述操作,我从 /proc/cpuinfo 中解析出cpu MHz"字符串,并将其转换为十进制.之后,就是一点数学,记住 1MHz = 1,000,000 个周期/秒,还有 10 亿纳秒/秒.

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 中的函数调用中查找经过的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆