为什么gprof明显低估了程序的运行时间?

Ang*_*gus 5 c profiling gprof

我有这个程序需要2.34秒才能运行,gprof表示它只需要1.18秒.我已经在其他地方读过答案,建议如果例如程序受I/O限制,gprof可能会出错,但这个程序显然不是.

这也适用于我试图描述的有用程序.这不是特定于这个琐碎的测试用例.

(同样在这种情况下,gprof表示main()占用了程序运行时间的100%以上,这是一个非常愚蠢的错误但不会给我带来麻烦.)

$ cat test.c
int main() {
    int i;
    for (i=0;i<1000000000;i++);
}

$ gcc test.c -o test

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gcc test.c -o test -pg

$ time ./test

real    0m2.342s
user    0m2.340s
sys 0m0.000s

$ gprof test |head
Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  Ts/call  Ts/call  name    
101.33      1.18     1.18                             main

 %         the percentage of the total running time of the
time       program used by this function.
Run Code Online (Sandbox Code Playgroud)

R..*_*R.. 3

我建议放弃gprof并切换到oprofile. 任何将检测插入到程序中的分析都会本质上影响性能,从而可能使结果出现偏差或无效。您不必oprofile构建具有分析支持的程序或获取特殊的支持分析的库;它通过统计方法工作,基本上对指令指针进行采样(在内核协助下)并使用样本计数来估计每个函数花费了多少时间。