I am doing tower of hanoi, and need calculate the time for the function. However,i try many type such as time.h or windows.h...Since the function is recursive and very fast to end. hence,the result always be 0 since time start -time end equal 0.So, I am here to ask all of the experts how i can get more precise time value...thanks alot..
If you still have problems timing your function, then try running it many times over in a loop. That'll give you a larger number, then you can divide the time taken by the number of iterations to see how well it performed.
> need calculate the time for the function. However,i try many type such as time.h or windows.h...
> Since the function is recursive and very fast to end. hence,the result always be 0.
Even if the result is not zero, a single measurement would tend to be somewhat inaccurate because the clock ticks at discrete intervals. The solution to both problems is: measure the approximate total time taken for a number of executions of the function (say a thousand times) and then compute the average time taken for a single execution.
#include <ctime>
#include <cstdlib>
#include <iostream>
int fn()
{
int r = 0 ;
for( int i = 0 ; i < 1000 ; ++i ) r += std::rand() % 2 ;
return r ;
}
int main()
{
// get an estimate of the processor time used
auto start = std::clock() ;
// operation to time
staticvolatileint v = 0 ;
constexprint N = 1000 ;
for( int i = 0 ; i < N ; ++i ) v += fn() ;
constdouble elapsed = std::clock() - start ;
std::cout << "approximate processor time for a single call of fn: "
<< (elapsed*1000000) / (CLOCKS_PER_SEC*N)
<< " microseconds\n" ;
}