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语言微基准测试及缓存影响评估最佳实践
- 无需专用工具的稳健测试方法有哪些?
- C社区常用的微基准测试工具是什么?
内容的提问来源于stack exchange,提问作者stefanobaghino
相关产品推荐
相关产品推荐

