【发布时间】:2019-01-10 18:08:17
【问题描述】:
我正在寻找一种干净的 c++11(直到 c++17)方法来编写一个函数,该函数只需使用给定的“开始”和“停止”时间(例如,给定间隔时间)将 fps 写入输出流. 所以我有这个代码,例如:
#include <iostream>
int main(int argc, char** argv) {
typedef std::chrono::high_resolution_clock time_t;
while (1) {
auto start = time_t::now();
// here is the call of function that do something
// in this example will be printing
std::cout << "Hello world!"
auto stop = time_t::now();
fsec_t duration = stop - start;
double seconds = duration.count();
double fps = (1.0 / seconds);
std::stringstream s;
s << "FPS: " << fps;
std::cout << s.str();
}
}
我想做类似的事情:
#include <iostream>
std::ostream & printFPS(std::ostream &stream, auto start);
int main(int argc, char** argv) {
while (1) {
auto start = std::chrono::high_resolution_clock::now();
// here is the call of function that do something
// in this example will be printing
std::cout << "Hello world!"
printFPS(std::cout, start);
}
}
std::ostream & printFPS(std::ostream &stream, auto start){
auto stop = std::chrono::high_resolution_clock::now();
std::chrono::duration<float> duration = stop - start;
double seconds = duration.count();
double fps = (1.0 / seconds);
std::stringstream s;
s << "FPS: " << fps;
return stream << s.str();
}
GCC 给了我提示'start'的推断类型是std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >,但我不想在函数中写这种类型(可能是推断会改变(?),而且它很长并且需要typedef) ,是否可以编写更优雅的函数,因为参数中不允许使用 auto ?谢谢!
【问题讨论】:
-
FYI
time_t对于时钟的类型来说是一个非常糟糕的选择。已经有一个类型,time_t,它代表一个时间单位(我很困惑阅读你的代码和看到time_t::now())。但是你用它来表示一个时钟,这是一个非常不同的东西。使用clock_t之类的东西会好得多。 -
另外,当我在这里时,使用 C++11 及更高版本,更喜欢
using而不是typedef。using clock_t = std::chrono::high_resolution_clock;更容易阅读,因为你介绍的名字总是在左边,而你别名的东西总是在右边(而不是typedef给我们的有时在中间的乐趣)。 -
哦,你是对的,它被添加为 main() 中的本地 typedef,只是为了提高可读性。我知道它可能会导致一些硬错误。感谢
using clock_t = std::chrono::high_resolution_clock;不知道这种语法