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

基于perf的CPU周期测量及函数执行时间精准度量咨询

代码执行时间与CPU周期数测量问题

问题背景与现有实践

我正在开展代码执行时间的测量工作,目前已能通过tracepoints测量函数执行耗时,但仍有两个需求待解决:

  • 测量funcB执行时占用的CPU周期数
  • 明确perf的时间测量原理:是简单计算Unix时间差,还是基于PMU计数器实现?

此前的实践步骤:

  • 编写了一个简单C程序,其中目标函数被调用20次,每次包含约1秒延迟
  • 编译时添加-g参数以包含调试信息
  • 使用perf probe在funcB的入口和返回处创建tracepoints
  • 通过perf record记录相关事件,再用perf script导出数据
  • 最后用Python脚本解析数据,成功绘制出funcB的执行时间图表

2023年4月29日更新

为直观展示CPU负载对测量结果的影响,我更新了C程序,实现对1万条数据的插入排序逻辑。分别在无CPU压力和有CPU压力的场景下运行程序并生成图表,结果显示CPU负载升高会导致函数执行时间明显增加。现咨询两个核心问题:

  • 是否可以测量不受CPU负载影响的函数精确执行时间?
  • 能否获取funcB执行时占用的CPU周期数(该指标理论上不受CPU负载影响)?

相关代码

第一个C程序

#include <stdio.h>
#include <unistd.h>

void funcB(int l){
    usleep(1000*l);
    printf("l=%d\n", l);
}

int main(){
    for (int i = 0; i < 20; i++){
      printf("i=%d\n", i);
      funcB(1000);
    }
    return 0;
}

更新后的C程序

#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <stdlib.h>

void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (int i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;
        
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

void funcB(int arr[], int n){
    insertionSort(arr, n);
}

int main(){
    for (int i = 0; i < 200; i++){
        int arr[10000];

        for (int f = 0; f < 10000 ;f++) {
            arr[f] = (rand() % 1000);
        }
        int n = sizeof(arr) / sizeof(arr[0]);
        printf("i=%d\n", i);
        funcB(arr, n);
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:57:38