获取自C++执行以来经过时间的最干净,最简单的方法
Cleanest and simplest way to get elapsed time since execution in C++
获取程序执行以来的时间(毫秒精度C++)的最简单,最干净的方法是什么?
我正在制作一个波干涉模拟器,以C++产生李萨如曲线。它需要自程序执行以来的时间(至少毫秒精度)才能运行。经过一番研究,我似乎找不到任何干净简单的方法来做到这一点。
所有<chrono>
功能对我来说似乎都非常混乱。Stack Overflow上的类似问题似乎要么无关,要么令人困惑(对我来说)要么不适用于我的情况。我尝试使用<time.h>
的函数,却发现它们的精度只有几秒钟。
我运行的是Windows 7 x64。该程序不必独立于平台,因为它供个人使用。任何帮助将不胜感激。
谢谢!
新的<chrono>
函数需要一点时间来适应,但是当您了解它们的工作原理时,它们使事情变得相当容易。
您的问题可以像这样解决,例如:
#include <chrono>
#include <thread>
#include <iostream>
// for readability
using hr_clock = std::chrono::high_resolution_clock;
using hr_time_point = hr_clock::time_point;
using hr_duration = hr_clock::duration;
using milliseconds = std::chrono::milliseconds;
int main()
{
// note the program start time
hr_time_point prog_start = hr_clock::now();
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
// find the duration
hr_duration d = hr_clock::now() - prog_start;
// cast the duration to milliseconds
milliseconds ms = std::chrono::duration_cast<milliseconds>(d);
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.n";
}
为方便起见,您可以创建一个函数来返回自上次调用该函数以来的时间:
milliseconds since_last_call()
{
// retain time between calls (static)
static hr_time_point previous = hr_clock::now();
// get current time
hr_time_point current = hr_clock::now();
// get the time difference between now and previous call to the function
milliseconds ms = std::chrono::duration_cast<milliseconds>(current - previous);
// store current time for next call
previous = current;
// return elapsed time in milliseconds
return ms;
}
int main()
{
since_last_call(); // initialize functions internal static time_point
// do stuff
std::this_thread::sleep_for(milliseconds(1000));
milliseconds ms = since_last_call();
// print out the number of milliseconds
std::cout << "time passed: " << ms.count() << " milliseconds.n";
}
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- 最简单的方法使多个指针一次指向同一位置,一次只处理2个位置
- 使用for循环制作位图的最简单和最有效的方法
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 编写要在 Python 中使用的并行 C/C++ 模块的最简单方法
- 开放式颜色多边形表面的最简单方法
- QT GUI最简单的方法可以从另一堂课访问MainWindow
- 确定代码中当前程序集是否为 32/64 位的最简单方法
- "永远"阻止线程的最简单便携式方法是什么?