這裏的行爲是代碼:86怪「CMP」指令
#include <iostream>
#include <time.h>
using namespace std;
#define ARR_LENGTH 1000000
#define TEST_NUM 0
typedef unsigned int uint;
uint arr[ARR_LENGTH];
uint inc_time(uint x) {
uint y = 0, tm = clock();
for (uint i = 0; i < x; i++) y++;
return clock() - tm;
}
int main() {
uint div = 0, mod = 0, tm = 0, overall = 0, inc_tm;
srand(time(NULL));
for (uint i = 0; i < ARR_LENGTH; i++) arr[i] = (uint)rand() + 2;
tm = clock();
for (uint i = 0; i < ARR_LENGTH - 1; i++)
if (arr[i] % arr[i+1] != TEST_NUM) mod++;
overall = clock() - tm;
inc_tm = inc_time(mod);
cout << "mods - " << mod << endl;
cout << "Overall time - " << overall<< endl;
cout << " wasted on increment - " << inc_tm << endl;
cout << " wasted on condition - " << overall - inc_tm << endl << endl;
tm = clock();
for (uint i = 0; i < ARR_LENGTH - 1; i++)
if (arr[i]/arr[i+1] != TEST_NUM) div++;
overall = clock()-tm;
inc_tm = inc_time(div);
cout << "divs - " << div << endl;
cout << "Overall time - " << overall << endl;
cout << " wasted on increment - " << inc_tm << endl;
cout << " wasted on condition - " << overall - inc_tm << endl << endl;
return 0;
}
如果你正在使用Visual Studio,只是編譯DEBUG(未釋放)模式,如果你使用GCC比禁用死代碼消除(-fno-dce
),否則代碼的某些部分將不起作用。
所以問題是:當您將TEST_NUM常量設置爲非零(例如5)時,兩個條件(模數和除法)都近似同時執行,但當您將TEST_NUM
設置爲0時,條件執行較慢(最多3次!)。爲什麼?
下面是反彙編列表:disassembly listing image http://img213.imageshack.us/slideshow/webplayer.php?id=wp000076.jpg
在0 test
指令的情況下是用來代替cmp X, 0
但即使你打補丁cmp X, 5
(在5時)至cmp X, 0
你會看到,它不會影響模數運算,但會影響分頻運算。
仔細觀察在改變TEST_NUM
常數時操作的次數和時間如何變化。
如果有人可以,請解釋這是怎麼發生的?
謝謝。
請您編輯您的問題以包含測試代碼;我不想要按照鏈接! –
在沒有優化的情況下編譯時,測試性能沒有多大意義。 – interjay
@OliCharlesworth我已經包含了代碼,但是如果你不想自己做反彙編上市,你仍然需要關注鏈接(對於我而言,這是在紙上,對不起) – n0p