温馨提示×

c++单次计时器怎么实现

c++
小亿
83
2024-03-16 17:38:46
栏目: 编程语言

实现一个单次计时器可以使用std::chrono库来实现。下面是一个简单的例子:

#include <iostream>
#include <chrono>
#include <thread>

int main() {
    auto start = std::chrono::high_resolution_clock::now(); // 记录开始时间

    // 模拟一些工作
    std::this_thread::sleep_for(std::chrono::seconds(3));

    auto end = std::chrono::high_resolution_clock::now(); // 记录结束时间

    std::chrono::duration<double> duration = end - start; // 计算时间间隔

    std::cout << "单次计时器: " << duration.count() << " 秒" << std::endl;

    return 0;
}

在这个例子中,我们使用std::chrono::high_resolution_clock来记录时间,并计算时间间隔。通过调用sleep_for函数来模拟一些工作,然后计算时间间隔并输出结果。您可以根据实际需求修改时间间隔和输出格式。

0