8

Possible Duplicate:
How to Calculate Execution Time of a Code Snippet in C++

How can I get the time spent by a particular set of statements in some C++ code?

Something like the time utility under Linux but only for some particular statements.

1
  • 1
    save the time just before the statements start executing, then let them execute, get the time again and substract the first time from it. Commented Oct 14, 2012 at 15:15

8 Answers 8

29

You can use the <chrono> header in the standard library:

#include <chrono> #include <iostream> unsigned long long fib(unsigned long long n) { return (0==n || 1==n) ? 1 : fib(n-1) + fib(n-2); } int main() { unsigned long long n = 0; while (true) { auto start = std::chrono::high_resolution_clock::now(); fib(++n); auto finish = std::chrono::high_resolution_clock::now(); auto microseconds = std::chrono::duration_cast<std::chrono::microseconds>(finish-start); std::cout << microseconds.count() << "µs\n"; if (microseconds > std::chrono::seconds(1)) break; } } 
Sign up to request clarification or add additional context in comments.

Comments

5

You need to measure the time yourself. The little stopwatch class I'm usually using looks like this:

#include <chrono> #include <iostream> template <typename Clock = std::chrono::steady_clock> class stopwatch { typename Clock::time_point last_; public: stopwatch() : last_(Clock::now()) {} void reset() { *this = stopwatch(); } typename Clock::duration elapsed() const { return Clock::now() - last_; } typename Clock::duration tick() { auto now = Clock::now(); auto elapsed = now - last_; last_ = now; return elapsed; } }; template <typename T, typename Rep, typename Period> T duration_cast(const std::chrono::duration<Rep, Period>& duration) { return duration.count() * static_cast<T>(Period::num) / static_cast<T>(Period::den); } int main() { stopwatch<> sw; // ... std::cout << "Elapsed: " << duration_cast<double>(sw.elapsed()) << '\n'; } 

duration_cast may not be an optimal name for the function, since a function with this name already exists in the standard library. Feel free to come up with a better one. ;)

Edit: Note that chrono is from C++11.

Comments

4

std::chrono or boost::chrono(in case that your compiler does not support C++11) can be used for this.

std::chrono::high_resolution_clock::time_point start( std::chrono::high_resolution_clock::now() ); .... std::cout << (std::chrono::high_resolution_clock::now() - start); 

2 Comments

it's high_resolution_clock, not high_resolution_timer
@BenoitBlanchon thank you and sorry for mistake, I edited my answer
2

You need to write a simple timing system. There is no built-in way in c++.

#include <sys/time.h> class Timer { private: struct timeval start_t; public: double start() { gettimeofday(&start_t, NULL); } double get_ms() { struct timeval now; gettimeofday(&now, NULL); return (now.tv_usec-start_t.tv_usec)/(double)1000.0 + (now.tv_sec-start_t.tv_sec)*(double)1000.0; } double get_ms_reset() { double res = get_ms(); reset(); return res; } Timer() { start(); } }; int main() { Timer t(); double used_ms; // run slow code.. used_ms = t.get_ms_reset(); // run slow code.. used_ms += t.get_ms_reset(); return 0; } 

Note that the measurement itself can affect the runtime significantly.

Comments

2

Possible Duplicate: How to Calculate Execution Time of a Code Snippet in C++

You can use the time.h C standard library ( explained in more detail at http://www.cplusplus.com/reference/clibrary/ctime/ ). The following program does what you want:

#include <iostream> #include <time.h> using namespace std; int main() { clock_t t1,t2; t1=clock(); //code goes here t2=clock(); float diff = ((float)t2-(float)t1)/CLOCKS_PER_SEC; cout << "Running time: " << diff << endl; return 0; } 

You can also do this:

int start_s=clock(); // the code you wish to time goes here int stop_s=clock(); cout << "time: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << endl; 

1 Comment

This is no good. If you count clocks per seconds, then you're going to get differences when the clock speed changes. That technology has existed since 2005. According to wikipedia: en.wikipedia.org/wiki/SpeedStep I have to downvote this.
1

If you are using GNU gcc/g++:

Try recompiling with --coverage, rerun the program and analyse the resulting files with the gprof utility. It will also print execution times of functions.

Edit: Compile and link with -pg, not with --coverage, --coverage is for gcov (which lines are actually executed).

1 Comment

Only my experience with -pg is that it breaks many calls with errno set to EINTR. Yes, it's easy to fix one such call or even two. If you have 100,000 lines of code, good luck with that...
0

Here's very fine snippet of code, that works well on windows and linux: https://stackoverflow.com/a/1861337/1483826
To use it, run it and save the result as "start time" and after the action - "end time". Subtract and divide to whatever accuracy you need.

3 Comments

A plain link to another answer isn't itself an answer. Please use the "flag" feature to signal duplicate questions.
@Mat: I am not sure whether mrowa has enough reputation to be able to flag yet...
@Mat: I like to credit origins, this is why I link to snippets instead of copying & pasting - still, you're quite right about the possible duplicate. (and yes, flagging right now is enabled from 15 rep)
-1

You can use #inclide <ctime> header. It's functions and their uses are here. Suppose you want to watch how much time a code spends. You have to take a current time just before start of that part and another current time just after ending of that part. Then take the difference of these two times. Readymade functions are declared within ctime to do all these works. Just checkout the above link.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.