获取自C++执行以来经过时间的最干净,最简单的方法

Cleanest and simplest way to get elapsed time since execution in C++

本文关键字:方法 最简单 时间 C++ 执行 经过 获取      更新时间:2023-10-16
获取

程序执行以来的时间(毫秒精度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";
}