Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 292
cryptograthor Avatar asked Mar 17 '17 20:03

cryptograthor


2 Answers

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.

like image 140
Howard Hinnant Avatar answered Nov 13 '22 23:11

Howard Hinnant


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

like image 22
HDJEMAI Avatar answered Nov 13 '22 22:11

HDJEMAI