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.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
user1717079
  • 493
  • 2
  • 4
  • 16
  • 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. – Ionut Hulub Oct 14 '12 at 15:15

8 Answers8

24

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;
    }
}
bames53
  • 86,085
  • 15
  • 179
  • 244
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.

cooky451
  • 3,460
  • 1
  • 21
  • 39
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);
BigBoss
  • 6,904
  • 2
  • 23
  • 38
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.

perh
  • 1,668
  • 11
  • 14
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;
Community
  • 1
  • 1
Rontogiannis Aristofanis
  • 8,883
  • 8
  • 41
  • 58
  • 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: https://en.wikipedia.org/wiki/SpeedStep I have to downvote this. – Joeppie Nov 30 '17 at 14:08
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).

Johannes Thoma
  • 1,026
  • 10
  • 21
  • 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... – Alexis Wilke Aug 15 '21 at 23:26
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.

Community
  • 1
  • 1
mrówa
  • 5,671
  • 3
  • 27
  • 39
  • 2
    A plain link to another answer isn't itself an answer. Please use the "flag" feature to signal duplicate questions. – Mat Oct 14 '12 at 15:18
  • @Mat: I am not sure whether mrowa has enough reputation to be able to flag yet... – Matthieu M. Oct 14 '12 at 15:30
  • @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) – mrówa Oct 14 '12 at 17:24
-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.

taufique
  • 2,701
  • 1
  • 26
  • 40