我一直在寻找精度很高的C ++时钟,我发现this answer的人使用std中的chrono库。然后,我尝试将所有持续时间放入向量中。我有一些问题。这是一个简单的测试代码:
#include <iostream>
#include <vector>
#include <chrono>
#include <stdlib.h>
int main() {
int i, j;
std::chrono::high_resolution_clock::time_point begin;
std::chrono::high_resolution_clock::time_point end;
// std::chrono::duration<long int, std::micro> duration;
std::vector<std::chrono::duration<long int, std::micro> > times;
for (i=0 ; i<10 ; ++i) {
begin=std::chrono::high_resolution_clock::now();
for (j=0 ; j<1000000 ; ++j) {
// Do things
}
end=std::chrono::high_resolution_clock::now();
auto duration=std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();
times.push_back(duration);
}
return EXIT_SUCCESS;
}
编译时出现此错误。 Gcc将该向量视为long int
向量,但我不明白为什么。
test.cpp:28:29: erreur: no matching function for call to ‘std::vector<std::chrono::duration<long int, std::ratio<1l, 1000000l> > >::push_back(long int&)’
times.push_back(duration);
我也尝试在第一个循环之前声明变量duration
,例如cpp reference example(并且没有自动变量)。但是,当我尝试为其分配值时,出现此错误:
test.cpp:26:13: erreur: no match for ‘operator=’ (operand types are ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >’ and ‘std::chrono::duration<long int, std::ratio<1l, 1000000l> >::rep {aka long int}’)
duration=std::chrono::duration_cast<std::chrono::microseconds>(end-begin).count();
我的问题:
duration
(不带auto
)?times
向量?答案 0 :(得分:2)
您快到了,只需在初始化.count()
的行末删除duration
。
- 我该如何声明可变持续时间(没有自动)?
- 我该如何声明时间向量?
最易读的形式是类型别名,例如
using Duration = std::chrono::microseconds;
std::vector<Duration> times;
const Duration d = std::chrono::duration_cast<Duration>(end - begin);
times.push_back(d);
请注意,我删除了显式表示模板参数long int
。 <chrono>
提供的默认帮助程序类型(此处为std::chrono::microseconds
)就可以了。