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

C语言微基准测试:clock与clock_gettime性能差异及缓存影响问询

测试环境
  • 硬件:M1 Pro芯片Mac
  • 系统:macOS Sonoma
  • 编译器:clang 15(clang-1500.0.40.1)
  • 编译选项:未开启显式优化(开启-O3后各测试版本差异极小,仅第三种代码略快)

三种shuffle函数性能测试方案及结果

方案一:循环外部单次计时

void test_performance() {
    // initialize only once to measure performance
    int ns[] = {1, 2, 3, 4, 5};
    int ops = 1E6;
    int start = clock();
    for (int i = 0; i < ops; i++) {
        shuffle(ns, 5);
    }
    int end = clock();
    double s_total = ((double) (end - start)) / CLOCKS_PER_SEC;
    double ns_op = s_total / ops * 1E9;
    printf("test_performance: %fns/op (%fs total) \n", ns_op, s_total);
}

测试结果:单操作耗时约30ns/op

方案二:循环内部逐次调用clock()计时

void test_performance() {
    // initialize only once to measure performance
    int ns[] = {1, 2, 3, 4, 5};
    int ops = 1E6;
    int start, end, ticks = 0;
    for (int i = 0; i < ops; i++) {
        start = clock();
        shuffle(ns, 5);
        end = clock();
        ticks += (end - start);
    }
    double s_total = ((double) ticks) / CLOCKS_PER_SEC;
    double ns_op = s_total / ops * 1E9;
    printf("test_performance: %fns/op (%fs total) \n", ns_op, s_total);
}

测试结果:程序整体运行明显变慢,单操作耗时增至约330ns/op
疑问:猜测是clock()的系统调用导致shuffle代码被频繁逐出CPU缓存,但不确定此量级差异的具体成因。

方案三:循环内部逐次调用clock_gettime()计时

void test_performance() {
    struct timespec start_time, end_time;
    // initialize only once to measure performance
    int ns[] = {1, 2, 3, 4, 5};
    int ops = 1E6;
    double s_total = 0;
    for (int i = 0; i < ops; i++) {
        if (clock_gettime(CLOCK_MONOTONIC, &start_time) != 0) {
            perror("clock_gettime");
            return;
        }
        shuffle(ns, 5);
        if (clock_gettime(CLOCK_MONOTONIC, &end_time) != 0) {
            perror("clock_gettime");
            return;
        }
        s_total += (end_time.tv_sec - start_time.tv_sec) + (end_time.tv_nsec - start_time.tv_nsec) / 1.0e9;
    }
    double ns_op = s_total / ops * 1E9;
    printf("test_performance: %fns/op (%fs total) \n", ns_op, s_total);
}

测试结果:单操作耗时约25ns/op;若将计时逻辑移至循环外部,结果回到约30ns/op
疑问:为何clock_gettime()没有出现clock()那样的性能损耗?


咨询内容

C语言微基准测试及缓存影响评估最佳实践

  1. 无需专用工具的稳健测试方法有哪些?
  2. C社区常用的微基准测试工具是什么?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 10:44:49