※ 引述《leicheong.bbs@bbs.sayya.org (理昌)》之銘言:
: 可是, instruction cache的cache miss絕對比data load instruction的
: cache miss影響要嚴重得多.
使用 const 不會增加 d-cache miss 或 i-cache miss.
之前提過了, 如果是常數的話, compiler 會和用 #define 一樣直接
以常數代入, 不會有你之前說的要去讀取 memory 的情況. 也就是
compiler 不會因為是使用 const, 就簡單地直譯成類似 "movl a, %eax"
這樣子的組語.
事實上用 const 和 #define 來定義常數, 一般的 compiler 會將其編譯
成同樣的組語. 以下面這個簡單地程式為例:
const int a=10; (或是 #define a 10)
int b=0;
...
b+=a;
最後 compiler 都是把 "b+=a" 那一行編譯成相同的組合語言:
movl b, %eax
addl $10, %eax
movl %eax, b
可以注意到, 即使是使用 const, 也不會去讀取 'a' 的值, 因此, 根本不會
去影響到 d-cache.
另外, 使用 const 只會影響到 symbol table 的大小, 除非用了幾千個 #define
常數, 對於 load time 的影響幾乎是沒有, 而且也不會影響到 i-cache, 因為
code print 和用 #define 是相同, 都是相同的 assembly codes.
綜合以上, 使用 const 不會增加 cache miss, 反而是用 #define 有可能會降低
執行效率 (如 string 的情況).
至於在 compile time 時 compiler 無法算出 const 或 #define 的值的情形, 如
以下的程式:
main() {
extern int A;
extern int B;
const int D=A+B; /* 或是 #define D (A+B) */
...
}
使用 #define 不但會把執行檔變大, 還會增加 i-cache miss 及 d-cache miss, 而
且在每一個用到 D 的地方都只是簡單地展開, 要重算一次 D 的值, 不像使用 const
重頭到尾只計算一次, 用 #define 是非常地沒有效率, 只有缺點而已.
加上之前提到的用 const 可以有不同的 scope, 幫助 debug, 及 complier 容易偵查
到 type mismatch 等優點, 使用 const 的好處是遠大於 #define, 而且在執行速率上
只會比 #define 好, 不會比用 #define 差.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 69.236.127.197