C 中的性能/分析测量 [英] Performance/profiling measurement in C
问题描述
我正在用 C 做一些原型设计工作,我想比较一个程序需要多长时间才能完成各种小的修改.
I'm doing some prototyping work in C, and I want to compare how long a program takes to complete with various small modifications.
我一直在使用clock
;来自 K&R:
I've been using clock
; from K&R:
clock
返回程序自执行开始使用的处理器时间,如果不可用,则返回 -1
.
clock
returns the processor time used by the program since the beginning of execution, or-1
if unavailable.
这对我来说似乎很明智,并且给出的结果与我的预期大致相符.但是有没有更好的方法可以用来查看哪些修改提高/降低了我的代码的效率?
This seems sensible to me, and has been giving results which broadly match my expectations. But is there something better to use to see what modifications improve/worsen the efficiency of my code?
更新:我对 Windows 和 Linux 都感兴趣;对两者都适用的东西将是理想的.
Update: I'm interested in both Windows and Linux here; something that works on both would be ideal.
更新 2:我对分析复杂问题的兴趣比简单程序从头到尾使用的总运行时间/时钟周期更不感兴趣——我已经知道我的程序的哪些部分很慢.clock
似乎符合这个要求,但我不知道它有多容易受到例如在后台运行的其他进程并占用处理器时间的影响.
Update 2: I'm less interested in profiling a complex problem than total run time/clock cycles used for a simple program from start to finish—I already know which parts of my program are slow. clock
appears to fit this bill, but I don't know how vulnerable it is to, for example, other processes running in the background and chewing up processor time.
推荐答案
在 POSIX(例如 Linux)中,您可以使用 gettimeofday()
以获得更高精度的计时值(微秒).
In POSIX (e.g. on Linux), you can use gettimeofday()
to get higher-precision timing values (microseconds).
在 Win32 中,QueryPerformanceCounter()
很受欢迎.
In Win32, QueryPerformanceCounter()
is popular.
谨防 CPU 时钟变化的影响,如果您的 CPU 在测试期间决定降低时钟频率,结果可能会出现偏差.
Beware of CPU clock-changing effects, if your CPU decides to clock down during the test, results may be skewed.
这篇关于C 中的性能/分析测量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!