James Raitsev
James Raitsev

Reputation: 96391

How to time event in C++?

I'd like to be able to get number of nanoseconds it takes to do something in my C++ program.

Object creation, time for a function to do it's thing etc.

In Java, we'd do something along the lines of:

    long now = System.currentTimeMillis();
    // stuff
    long diff = (System.currentTimeMillis() - now);

How would you do the same in C++?

Upvotes: 4

Views: 8719

Answers (5)

bames53
bames53

Reputation: 88155

The <chrono> library in standard C++ provides the best way to do this. This library provides a standard, type safe, generic API for clocks.

#include <chrono>
#include <iostream>

int main() {
    using std::chrono::duration_cast;
    using std::chrono::nanoseconds;
    typedef std::chrono::high_resolution_clock clock;

    auto start = clock::now();
    // stuff
    auto end = clock::now();
    std::cout << duration_cast<nanoseconds>(end-start).count() << "ns\n";
}

The actual resolution of the clock will vary between implementations, but this code will always show results in nanoseconds, as accurately as possible given the implementation's tick period.

Upvotes: 9

SChepurin
SChepurin

Reputation: 1854

In C++11 you can do it using chrono library where -

Class template std::chrono::duration represents a time interval. It consists of a count of ticks of type Rep and a tick period, where the tick period is a compile-time rational constant representing the number of seconds from one tick to the next.

Currently implemented in GCC 4.5.1. (not yet in VC++). See sample code from cppreference.com on Ideone.com execution time of a function call

Upvotes: 2

user2138149
user2138149

Reputation: 16659

I asked this exact question earlier today. The best solution I have at the moment is to use SDL, and call:

uint32 a_time = SDL_GetTicks(); // Return uint32 count of milliseconds since SDL_Init was called

Although this is probably going to give you lots of overhead, even if you just init SDL with the timer functionality. (SDL_Init(SDL_INIT_TIMER).

Hope this helps you - I settled for this as a solution because it is portable.

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258608

Take a look at clock and clock_t. For the resolution you're talking about, I don't think there's native support in C++. To get meaningful values, you'll have to time multiple calls or constructions, or use a profiler (desired).

Upvotes: 1

Related Questions