1

I was looking for a clock in C++ with a good precision and I found this answer who use the chrono library from std. I then tried to put all durations in a vector. And I've some problems. Here is a simple test code:

#include <iostream>
#include <vector>

#include <chrono>

#include <stdlib.h>

int main() {
  int i, j;

  std::chrono::high_resolution_clock::time_point begin;
  std::chrono::high_resolution_clock::time_point end;

//  std::chrono::duration<long int, std::micro> duration;

  std::vector<std::chrono::duration<long int, std::micro> > times;

  for (i=0 ; i<10 ; ++i) {

    begin=std::chrono::high_resolution_clock::now();
    for (j=0 ; j<1000000 ; ++j) {
      // Do things
    }
    end=std::chrono::high_resolution_clock::now();

    auto duration=std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();

    times.push_back(duration);

  }


  return EXIT_SUCCESS;
}


When I compile, I got this error. Gcc consider the vector as a long int vector, and I don't understand why.

test.cpp:28:29: erreur: no matching function for call to ‘std::vector<std::chrono::duration<long int, std::ratio<1l, 1000000l> > >::push_back(long int&)’
     times.push_back(duration);


I also tried to declare the variable duration before the first loop, like the cpp reference example (and without the auto). But, when I try to assign it a value I got this error:

test.cpp:26:13: erreur: no match for ‘operator=’ (operand types are ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >’ and ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >::rep {aka long int}’)
     duration=std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();



My questions:

  • How do I have to declare the variable duration (without the auto)?
  • How do I have to declare the times vector ?
Phantom
  • 833
  • 1
  • 9
  • 26

1 Answers1

2

You are almost there, just remove the .count() at the end of line in which you initialize duration.

  • How do I have to declare the variable duration (without the auto)?
  • How do I have to declare the times vector ?

The most readable form is a type alias, e.g.

using Duration = std::chrono::microseconds;

std::vector<Duration> times;

const Duration d = std::chrono::duration_cast<Duration>(end - begin);

times.push_back(d);

Note that I have dropped the explicit representation template parameter long int. The default helper types that <chrono> provides (here, std::chrono::microseconds) are fine.

lubgr
  • 37,368
  • 3
  • 66
  • 117