Timer to find elapsed time in a function call in C

2019-01-18 08:13发布

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 please provide a sample code-snippet.

Pseudo code

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

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

11条回答
三岁会撩人
2楼-- · 2019-01-18 08:35

You are asking for something that is not possible this way. You would need HW level support to get to that level of precision and even then control the variables very carefully. What happens if you get an interrupt while running your code? What if the OS decides to run some other piece of code?

And what does your code do? Does it use RAM memory? What if your code and/or data is or is not in the cache?

In some environments you can use HW level counters for this job provided you control those variables. But how do you prevent context switches in Linux?

For instance, in Texas Instruments' DSP tools (Code Composer Studio) you can profile the code very exactly because the whole debugging environment is set such that the emulator (e.g. Blackhawk) receives info about every operation run. You can also set watchpoints which are coded directly into a HW block inside the chip in some processors. This works because the memory lanes are also routed to this debugging block.

They do offer functions in their CSL's (Chip Support Library) which are what you are asking for with the timing overhead being a few cycles. But this is only available for their processors and is completely dependant on reading the timer values from the HW registers.

查看更多
看我几分像从前
3楼-- · 2019-01-18 08:38

I don't know if you'll find any timers that provide resolution to a single nanosecond -- it would depend on the resolution of the system clock -- but you might want to look at http://code.google.com/p/high-resolution-timer/. They indicate they can provide resolution to the microsecond level on most Linux systems and in the nanoseconds on Sun systems.

查看更多
戒情不戒烟
4楼-- · 2019-01-18 08:40

Can you just run it 10^9 times and stopwatch it?

查看更多
贼婆χ
5楼-- · 2019-01-18 08:44

Any timer functionality is going to have to be platform-specific, especially with that precision requirement.

The standard solution in POSIX systems is gettimeofday(), but it has only microsecond precision.

If this is for performance benchmarking, the standard way is to make the code under test take enough time to make the precision requirement less severe. In other words, run your test code for a whole second (or more).

查看更多
别忘想泡老子
6楼-- · 2019-01-18 08:48

There is no timer in c which has guaranteed 1 nanosecond precision. You may want to look into clock() or better yet The POSIX gettimeofday()

查看更多
登录 后发表回答