I want to measure the time taken by my C++ program however, if I use:
time_t begin, end;
func(); //my function...it contains the code whose elapsed time I want to measure
cout<<"\n Time elapsed:"<<difftime(end, begin) <<" seconds"<<endl;
The time elapsed that I am getting is 0 seconds.
Also gprof does not work in my case as it shows that it cannot allocate the amount of memory, as is required by my program.
Is there some other way out to measure the amount of time required by my program. Valgrind's massif tool does show the time taken by the snapshot but the documentation does not mention whether it is in milliseconds or microseconds.
Please suggest a suitable way?
It would be nice if i can measure the time in milli-seconds.
you may also want to look at facebook's benchmarking utility.
You could use code as shown below.
clock_t start = clock(); // Code here... clock_t ticks = clock()-start; std::cout << "Time Taken:" << (double)ticks/CLOCKS_PER_SEC << "\n";
One possibility would be to spawn the program yourself (
CreateProcess on Windows,
fork on Unix-like systems). Then, wait for the child to exit (
WaitForSingleObject on Windows,
waitpid on Unix). Finally, get the times for the child process (
GetProcessTimes on Windows,
times on Unix).
This will give times in milliseconds, and separates wall time from CPU time. The latter is particularly handy when/if you have other stuff running on the same system at the same time (you still get better accuracy with a quiescent system, but can stay reasonably close).