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

问题描述 投票:6回答:2

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

我想我希望这个表是一个字符串。我目前无法解决如何将chrono转换为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
}
c++ string type-conversion chrono
2个回答
6
投票

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

要流式传输chrono::duration,你可以使用它的.count()成员函数,然后你可能想要添加单位(例如ns或任何单位)。

这个免费的,仅限标题的开源库:https://howardhinnant.github.io/date/chrono_io.html可以通过自动为您添加单位来更轻松地流式传输duration

例如:

#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';
}

只为我输出:

0µs

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

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

还有可以使用的to_string系列:

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

然而,没有to_string直接来自chrono::duration。你必须用.count()“逃脱”,然后添加单位(如果需要)。


5
投票

你可以像这样使用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;
}

结果:

- 很快:

0秒

- 以μs为单位:

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

结果:

535971ms

© www.soinside.com 2019 - 2024. All rights reserved.