将chrono :: duration转换为字符串或C字符串

7l-*_*l04 7 c++ string type-conversion c++-chrono

我正在尝试创建一个表(一个9乘11的数组),它存储一个函数通过几个排序函数所花费的时间.

我想我希望这个表是一个字符串.我目前无法解决如何转换chronostring并且无法在线查找任何资源.

我是否需要放弃表格的字符串输入,或者有没有办法将这些时间差异存储在字符串中?

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
}
Run Code Online (Sandbox Code Playgroud)

How*_*ant 8

您需要流式传输到a std::ostringstream,然后从该流中检索字符串.

要流式传输,chrono::duration您可以使用其.count()成员函数,然后您可能想要添加单位(例如,ns或者单位是什么).

这个免费的,仅限标题的开源库:https: //howardhinnant.github.io/date/chrono_io.htmlduration通过自动为您附加单元来简化流式传输.

例如:

#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';
}
Run Code Online (Sandbox Code Playgroud)

只为我输出:

0µs
Run Code Online (Sandbox Code Playgroud)

没有"chrono_io.h"它看起来更像是:

    out << chrono::duration<double>(t1 - t0).count() << 's';
Run Code Online (Sandbox Code Playgroud)

还有to_string可以使用的家庭:

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

有没有to_string直接从该去chrono::duration但是.你必须"逃避" .count(),然后添加单位(如果需要).


HDJ*_*MAI 6

您可以这样使用chrono::duration_cast

#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;
}
Run Code Online (Sandbox Code Playgroud)

结果:

- 很快:

0秒

-以µs为单位:

auto x = chrono::duration_cast<chrono::microseconds>(elapsed_seconds);
Run Code Online (Sandbox Code Playgroud)

结果:

535971µs