user224266
user224266

Reputation: 61

What is the default unit of time of c++'s chrono?

I used this code to measure the runtime of my program from this answer

auto start = std::chrono::system_clock::now();

/* do some work */

auto end = std::chrono::system_clock::now();
auto elapsed = end - start;
std::cout << elapsed.count() << '\n';

I only needed to measure the runtime to look for a trend but I am kind of curious as to what unit that is.

Upvotes: 4

Views: 5324

Answers (2)

for_stack
for_stack

Reputation: 22896

It's unspecified by the standard.

20.12.7.1 Class system_clock [time.clock.system]
Objects of class system_clock represent wall clock time from the system-wide realtime clock.
class system_clock {
public:
typedef see below rep;
typedef ratio< unspecified , unspecified > period;
typedef chrono::duration< rep, period> duration;
typedef chrono::time_point time_point;
static constexpr bool is_steady = unspecified ;
static time_point now() noexcept;
// Map to C API
static time_t to_time_t (const time_point& t) noexcept;
static time_point from_time_t(time_t t) noexcept;
};
typedef unspecified system_clock::rep;

Personally, I think it's always a good idea to explicitly convert the result to some specific duration you want.

Upvotes: 2

BiagioF
BiagioF

Reputation: 9705

You can easily check by your self, with this code:

using Clock = std::chrono::system_clock;
using Duration = Clock::duration;
std::cout << Duration::period::num << " , " << Duration::period::den << '\n';

On my system it prints:

 1 , 1000000000

That is, a period in terms of nanoseconds (i.e. 10−9s).

Upvotes: 4

Related Questions