【问题标题】:How to divide time (chrono) by a given value如何将时间(chrono)除以给定值
【发布时间】:2018-11-30 02:25:17
【问题描述】:

我正在努力熟悉 chrono 以评估性能。我有一个全局变量,它收集从文件中插入单词到字符串向量的时间。如果我插入了 n 个字符串,我如何将该时间除以 n 以获得平均时间并将其转换为秒、微秒、毫秒?我找到了如何将计时时间除以另一个计时,但找不到如何除以给定的数字 n。这是我尝试过的:

//global var
auto InsertionTimerChainingHT = std::chrono::system_clock::now();
//... function declerations
// inside function where I insert strings to vector
auto total = std::chrono::system_clock::now();
for (auto it = DataArray.begin(); it != DataArray.end(); it++)
{
    auto start = std::chrono::system_clock::now();
    ChainingHT.insert(it->data());
    auto stop = std::chrono::system_clock::now();

    total += (stop - start);


}
InsertionTimerChainingHT = total;
// I attempted to do the following
InsertionTimerChainingHT /= 1853;
InsertionTimerChainingHT = (InsertionTimerChainingHT / 1853).count();

【问题讨论】:

  • 使用std::chrono::duration<double> diff = start - stop; 以秒为单位获取时间。为什么要除以 1853?
  • @BarmakShemirani 感谢您让我知道如何以秒为单位进行转换。 1853 是我在给定时间跨度内插入的项目数量。我正在尝试获取插入字符串的平均时间。

标签: c++ time chrono


【解决方案1】:

将您的total 存储为chrono::duration,而不是chrono::time_pointsystem_clock::now() 的返回是 time_point(时间的瞬间)。 stopstart 之间的区别是 duration(比如 3 微秒)。

例如:

auto total = std::chrono::system_clock::duration{0};  // zero system_clock ticks

duration可以除以一个标量,得到duration

total /= DataArray.size();

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多