sta*_*wer 3 c++ c++11 c++14 c++17
我正在搜索一个干净的c ++ 11(最多c ++ 17)方法来编写一个函数,该函数只需将fps写入输出流,并给定'start'和'stop'次(例如给定一个间隔时间).所以我有这个代码,例如:
#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();
}
}
Run Code Online (Sandbox Code Playgroud)
我想做的事情如下:
#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();
}
Run Code Online (Sandbox Code Playgroud)
GCC给了我一些提示,推断出'start'的类型std::chrono::time_point<std::chrono::_V2::system_clock, std::chrono::duration<long int, std::ratio<1, 1000000000> > >
,但我不想写函数这个类型(可能是演绎会改变(?),也很长,需要typedef),是否可以写更优雅的功能,因为不允许自动参数?谢谢!
您可以使用它decltype
来推断时间类型并将其用作参数的类型.
using time_type = decltype(std::chrono::high_resolution_clock::now());
std::ostream & printFPS(std::ostream &stream, time_type start);
Run Code Online (Sandbox Code Playgroud)
表达式std::chrono::high_resolution_clock::now()
返回type的值std::chrono::high_resolution_clock::time_point
.所以你可以直接这样做:
std::ostream& printFPS(std::ostream&, std::chrono::high_resolution_clock::time_point );
Run Code Online (Sandbox Code Playgroud)
但是你的打印功能可能并不关心你从哪个时钟开始time_point
.它只关心它有一个time_point
,所以你可以更普遍地做到这一点:
template <typename Clock, typename Duration>
std::ostream& printFPS(std::ostream&, std::chrono::time_point<Clock, Duration> );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
159 次 |
最近记录: |