the time taken to call clock() would be much lower than the resolution of the clock provided by the library.
#include <iostream>
#include <ctime>
using namespace std ;
int main()
{
const double res = 1000.0 / CLOCKS_PER_SEC ;
cout << "resolution of libc clock: " << res << " millisecs\n" ;
int ncalls = 0 ;
enum { NTESTS = 1024 } ;
for( int i=0 ; i<NTESTS ; ++i )
{
clock_t t1 = clock(), t2 = t1+1 ;
while( clock() == t1 ) ;
while( clock() == t2 ) ++ncalls ;
}
cout << "time taken to call clock: " << NTESTS * res / ncalls << " millisecs\n" ;
}
/*
>g++ -O3 -march=pentium4 -Wall -std=c++98 clock_time.cpp && ./a.out
resolution of libc clock: 7.8125 millisecs
time taken to call clock: 0.00506795 millisecs
*/
since the clock ticks are at discrete intervals, there can be an error of upto one clock tick in a single measurement. for example,
|--------|
S+++++++|++++++++|++++++++|++++++++|++++++++|+++++++
E|--------|--------| 5 ticks
|--------|-------
S|++++++++|++++++++|++++++++|++++++++|++++++++|+++++
E--|--------| 6 ticks
we can clearly make this out in the difference between the min and max times posted earlier. to minimize the statistical expectation of error
a. the time measured should be an order of magnitude higher than the resolution of the clock.
b. run the test several times; the average should then give a better indication
the time taken to call clock one or two times would be negigible in comparison.
if you are attempting to profile your code for identifying and removing performance bottlenecks, you should use a standard profiler. a good profiler would (approximately) adjust for the profiling overhead while reporting time information.