Convert chrono::duration to string or C string

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.


You can use chrono::duration_cast like this:

#include <iostream>
#include<chrono>
#include <sstream>

using namespace std;

int main()
{
    chrono::time_point<std::chrono::system_clock> start, end;
    start = chrono::system_clock::now();
    //Sort Array Here
    end = chrono::system_clock::now();
    chrono::duration<double> elapsed_seconds = end - start;
    auto x = chrono::duration_cast<chrono::seconds>(elapsed_seconds);

    //to_string
    string result = to_string(x.count());

    cout <<  result;
}

result:

- In seconds:

0 seconds

- In µs:

auto x = chrono::duration_cast<chrono::microseconds>(elapsed_seconds);

result:

535971µs