jeudi 2 avril 2020

C++11 or newer: most succinct idiom for high resolution timing?

The following code works but the clock period verbosity is absurd.

First, I would have guessed that the duration<> would be in units of "1" but since the now() is in ratio<1,1000000000> duration is too, am I correct?

I have trouble understanding why ratio wouldn't have an implicit conversion operator to double for instance; if I just use chrono::high_resolution_clock::period by itself in a numerical context I wonder why it doesn't simply do the division for me?

auto timepointBegin = chrono::high_resolution_clock::now();

// do something worth timing

auto timepointEnd  = chrono::high_resolution_clock::now();

chrono::duration<double> dur = timepointEnd - timepointBegin;

printf( "Total test time: %f sec", dur.count() *
          chrono::high_resolution_clock::period::num /
          chrono::high_resolution_clock::period::den );

I read that std::chrono::seconds is basically typedef duration <long,ratio<1,1>> but using that to replace the type of dur below gives the error of tstopMT.cxx:67:38: error: conversion from 'duration<[...],ratio<[...],1000000000>>' to non-scalar type 'duration<[...],ratio<[...],1>>' requested . Maybe my eyes are failing me but those look like convertible types? Also I think that'd be a disaster as it stores seconds in an int, right?

So I tried making the type chrono::duration<double,ratio<1,1>> instead but also no joy; it's not adjusting for the fact that now() is returning nanoseconds. Why not?

Aucun commentaire:

Enregistrer un commentaire