当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to measure the amount of time taken by program

问题描述:

I want to measure the time taken by my C++ program however, if I use:

time_t begin, end;

time_t(&begin);

func(); //my function...it contains the code whose elapsed time I want to measure

time(&end);

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.

网友答案:

Use std::chrono.
http://en.cppreference.com/w/cpp/chrono/duration

you may also want to look at facebook's benchmarking utility.
https://github.com/facebook/folly/blob/master/folly/docs/Benchmark.md

网友答案:

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).

分享给朋友:
您可能感兴趣的文章:
随机阅读: