I used clock_gettime() to calculate the time taken for an operation.But it gives time only in milliseconds precision.
But if i need time in nano seconds precision which API should i use. There is a difficulty in using ClockCycles() as the start time is taken by one thread and end time taken by another thread. So not able to lock the thread to single CPU when using ClockCycles().
You seem to have a basic misunderstanding of the interaction of the hardware and the OS. I’ll try to help out here.
There are two times of importance.
How often the timer interrupt is fired.
The cpu frequency
#1 is relatively slow. This limits the accuracy of any OS calls. clock_gettime() is one of these. It doesn’t matter whether you get the time in microseconds or nanoseconds if the interrupt is firing only once a millisecond. There is no more accuracy to squeeze out of it.
#2 is very fast, in nanoseconds. However it’s use is problematic. It’s a feature of the Pentium processor that you can read a counter that is incremented by 2. This is a hardware feature, not an OS feature. The call to read it doesn’t take account of scheduling, which processor your thread is running on, or roll over. To use it accurately you would have to lock the thread to a processor, run at the highest priority or turn off interrupts, and take steps to deal with roll over. If your program might run on different hardware, you have to have a way to determine the actual frequency, which can differ. It’s one good feature is high resolution.
I previously mentioned an alternative, which is to find some hardware with a high frequency timer or counter.