Search code examples
c++11c++-chrono

printing to file the duration of chrono


I'm trying to print to the file amount of microseconds:

high_resolution_clock::time_point t1 = high_resolution_clock::now();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
auto duration1 = duration_cast<microseconds> (t2-t1).count();

fprintf(file, "%lu, %lu\n", dutation1, duration1);

In the file I can see the first column having some values around 2000 but I get second column values always equal to zero. I wonder if I'm doing correct fprintf (the %lu parameter) and why does it print the second variable as zero in the file?


Solution

  • The count function returns a type called rep, which according to this std::duration reference is

    an arithmetic type representing the number of ticks

    Since you don't know the exact type, you can't really use any printf function to print the values, since if you use the wrong format you will have undefined behavior (which is very likely what you have here).

    This will be easily solved if you use C++ streams instead, since the correct "output" operator << will automatically be selected to handle the type.