C #define 中的常量公式是否会影响效率?

Is there an efficiency hit for a constant formula in a C #define?

我正在仔细阅读来自 cpufreq_governor.h 的一些内核源代码并看到了这个:

/*
 * The polling frequency depends on the capability of the processor. Default
 * polling frequency is 1000 times the transition latency of the processor. The
 * governor will work on any processor with transition latency <= 10ms, using
 * appropriate sampling rate.
 *
 * For CPUs with transition latency > 10ms (mostly drivers with CPUFREQ_ETERNAL)
 * this governor will not work. All times here are in us (micro seconds).
 */
#define MIN_SAMPLING_RATE_RATIO         (2)
#define LATENCY_MULTIPLIER          (1000)
#define MIN_LATENCY_MULTIPLIER          (20)
#define TRANSITION_LATENCY_LIMIT        (10 * 1000 * 1000)

最后一行改成这样会不会效率更高:

#define TRANSITION_LATENCY_LIMIT        (10000000) /* (10 * 1000 * 1000) */

Would it not be more efficient to change the last line to read:

#define TRANSITION_LATENCY_LIMIT        (10000000) /* (10 * 1000 * 1000) */

很可能不会有任何区别。

任何半正经的编译器都应该能够在编译时计算 10 * 1000 * 1000

问问自己:

您的建议中有多少个零(或备选方案,数字是多少)

#define TRANSITION_LATENCY_LIMIT (10000000)

累人的任务。这更加直观和容易(并且易于维护):

#define TRANSITION_LATENCY_LIMIT (10 * 1000 * 1000)

此外,(10 * 1000 * 1000) 是更方便的表示 10 微秒的方法(10 乘以百万分之一 (1000 * 1000) 秒)

此外,这里的效率无关紧要,因为它将由编译器计算。

毫无疑问,您更改它并获得更高效的代码,因为与加法和减法相比,乘法需要更多 CPU 循环比较,但您失去了源代码的代码可读性。但不要担心,今天的编译器非常聪明,可以在编译时完成它,这个过程被称为代码优化。