Timer to find elapsed time in a function call in C

后端 未结 11 1618
故里飘歌
故里飘歌 2020-12-09 14:20

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

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

If yes ple

11条回答
  •  萌比男神i
    2020-12-09 14:59

    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))
    

    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; 
    }
    

    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.

    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.

提交回复
热议问题