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
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.
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.
Can you just run it 10^9 times and stopwatch it?
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).
There is no timer in c which has guaranteed 1 nanosecond precision. You may want to look into
clock()
or better yet The POSIXgettimeofday()