I wanted to time how long it took for one of my functions to run yesterday and it ended up taking me a little bit of time to track down how to do this in C++ on a Linux box, so I thought I’d throw up the code here.
#include <sys/time.h> #include <iostream> using namespace std; int main() { struct timeval start_time; struct timeval end_time; gettimeofday(&start_time, NULL); aFunction(someParams); // function to be timed gettimeofday(&end_time, NULL); // get difference, multiply by 1E-6 to convert to seconds float duration = (end_t.tv_sec - start_t.tv_sec) + (end_time.tv_usec - start_time.tv_usec) * 1E-6; cout << "duration: " << duration << "s" << endl; }
And that’s it! Not too much to it, but was a little difficult to track down.
Reblogged this on Gigable – Tech Blog.
You should note, that this only approximates the actual running time of a function, and cannot reliably measure it. If the operating system decides to unschedule the process of which this function is part of and schedule some other process instead, the run-time of the other process will be included in your benchmark. If your function is very short though, this is unlikely.
If you want the actual time taken to run the function, you need the times() function. Have a look at http://www.gnu.org/software/libc/manual/html_node/Time-Basics.html to see about the different meanings of the word “time” in a technical context.
Thanks for the info, very helpful! 🙂