Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing the execution of statements - C++ [duplicate]

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.

like image 474
user1717079 Avatar asked Oct 14 '12 15:10

user1717079


1 Answers

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;
    }
}
like image 146
bames53 Avatar answered Oct 16 '22 02:10

bames53