Search code examples
c++stringtype-conversionc++-chrono

Convert chrono::duration to string or C string


I'm trying to make a table (a 9 by 11 array) that stores the amount of time taken by a function by several sorting functions.

I think I want the table to be a string. I currently cannot solve how to convert chrono to string and haven't been able to find any resources online.

Do I need to abandon the string typing for the table, or is there a way to store these time differences in a string?

for (int i = 0; i<8;i++) // sort 8 different arrays
{ 
    start = chrono::system_clock::now(); 
    //Sort Array Here
    end = chrono::system_clock::now();
    chrono::duration<double> elapsed_seconds = end-start;
    table[1][i] = string(elapsed_seconds)   // error: no matching conversion for functional style cast
}

Solution

  • You'll need to stream into a std::ostringstream, and then retrieve the string from that stream.

    To stream a chrono::duration you could use its .count() member function, and then you might want to add units (e.g. ns or whatever the unit is).

    This free, header-only, open-source library: https://howardhinnant.github.io/date/chrono_io.html makes it easier to stream a duration by automatically appending the units for you.

    For example:

    #include "chrono_io.h"
    #include <iostream>
    #include <sstream>
    
    int
    main()
    {
        using namespace std;
        using namespace date;
        ostringstream out;
        auto t0 = chrono::system_clock::now();
        auto t1 = chrono::system_clock::now();
        out << t1 - t0;
        string s = out.str();
        cout << s << '\n';
    }
    

    Just output for me:

    0µs
    

    Without "chrono_io.h" it looks more like:

        out << chrono::duration<double>(t1 - t0).count() << 's';
    

    There's also the to_string family that could be used:

        string s = to_string(chrono::duration<double>(t1 - t0).count()) + 's';
    

    There is no to_string that goes directly from a chrono::duration however. You have to "escape" out with .count() and then add units (if desired).


    Update

    C++20 brings the functionality of "chrono_io.h" straight into <chrono>. So no longer a need for the free open-source library.