You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++11 chrono库出现前,开发者如何实现时间测量?

C++11 及以后的标准时间测量方式

自C++11起,我们可以通过标准库中的chrono组件实现精准的时间测量,示例代码如下:

#include <iostream>
#include <chrono>
 
long fibonacci(unsigned n)
{
    if (n < 2) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}
 
int main()
{
    auto start = std::chrono::steady_clock::now();
    std::cout << "f(42) = " << fibonacci(42) << '\n';
    auto end = std::chrono::steady_clock::now();
    std::chrono::duration<double> elapsed_seconds = end-start;
    std::cout << "elapsed time: " << elapsed_seconds.count() << "s\n";
}
C++11 之前的时间测量方案

在chrono库诞生前,标准C++层面没有统一的高精度时间测量接口,开发者主要依赖以下两类方案:

1. 基于C标准库的低精度实现

可以借助C标准库<time.h>中的函数完成基础时间统计:

  • time():返回从纪元(通常为1970年1月1日00:00:00)到当前的秒数,精度仅为秒级,适合粗略的时间跨度统计。
  • clock():返回程序运行以来消耗的CPU时钟周期数,将其除以CLOCKS_PER_SEC可转换为秒数,但这个值代表的是程序占用的CPU时间,而非实际流逝的墙钟时间,且CLOCKS_PER_SEC的定义可能因平台而异。

示例代码:

#include <iostream>
#include <time.h>

long fibonacci(unsigned n)
{
    if (n < 2) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}

int main()
{
    // 测量CPU时间
    clock_t cpu_start = clock();
    std::cout << "f(42) = " << fibonacci(42) << '\n';
    clock_t cpu_end = clock();
    double cpu_elapsed = static_cast<double>(cpu_end - cpu_start) / CLOCKS_PER_SEC;
    std::cout << "CPU time used: " << cpu_elapsed << "s\n";

    // 测量墙钟时间
    time_t wall_start = time(nullptr);
    fibonacci(42);
    time_t wall_end = time(nullptr);
    std::cout << "Wall time elapsed: " << difftime(wall_end, wall_start) << "s\n";
}

2. 操作系统专属的高精度API

如果需要微秒甚至纳秒级的精度,必须依赖平台特定的系统调用:

  • Windows平台:使用QueryPerformanceCounter()获取高精度计数器值,配合QueryPerformanceFrequency()将计数器值转换为实际时间,精度可达微秒级。
  • Linux/Unix平台:使用gettimeofday()(微秒精度)或clock_gettime()(纳秒精度,属于POSIX标准,多数Unix-like系统支持)。

Linux平台示例代码:

#include <iostream>
#include <sys/time.h>

long fibonacci(unsigned n)
{
    if (n < 2) return n;
    return fibonacci(n-1) + fibonacci(n-2);
}

int main()
{
    struct timeval start, end;
    gettimeofday(&start, nullptr);
    std::cout << "f(42) = " << fibonacci(42) << '\n';
    gettimeofday(&end, nullptr);
    double elapsed = (end.tv_sec - start.tv_sec) + static_cast<double>(end.tv_usec - start.tv_usec) / 1e6;
    std::cout << "elapsed time: " << elapsed << "s\n";
}

总而言之,C++11之前没有跨平台的标准高精度时间测量方案,开发者要么接受C标准库的低精度限制,要么针对不同平台编写适配代码。

内容的提问来源于stack exchange,提问作者KcFnMi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 22:40:25