AvZ*_*AvZ 3 c++ time execution-time elapsedtime
在C++中执行程序(精确到毫秒)后,最简单,最干净的方法是什么?
我正在制作一个波浪干涉模拟器,用C++ 生成Lissajous曲线.它需要自执行程序(精度至少为毫秒)起的时间才能运行.经过一些研究后,我似乎无法找到任何干净简单的方法.
所有<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";
}
Run Code Online (Sandbox Code Playgroud)
为方便起见,您可以创建一个函数来返回自上次调用该函数以来的时间:
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";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
245 次 |
| 最近记录: |