2013-02-08 47 views
0

我熟悉一個科學流體動力學代碼。該代碼幾乎總是使用預處理器指令,例如,預處理器標誌與(例如)布爾標誌

#ifdef PARTICLES 
    int nghost = 5 
#else 
    int nghost = 4 
#endif 

代替簡單C標誌位,等等,

int nghost = 4; 
if(particlesFlag) { nghost = 5; } 

預處理器標誌的缺點是,(在該框架)它需要用於每一個問題設置之前的結構(帶有報頭文件創建)每個版本,使用c代碼標誌只需要重新編譯。

這種方法的優點是什麼?

效率的任何提升看起來似乎都非常小 - 特別是因爲這個代碼(例如)只在程序初始化時運行一次,而所有真正的勞動都在不同的循環中發生處理器等

回答

0

說我有成千上萬的API使用nghost。如果已經定義了PARTICLES,則在預處理期間,所有這些變量將被其他5個替換爲4。

你說的是單個實例,一個大項目就是預處理很有用的地方。

想想這個。

int x() { int a = nghost *5; } 
int ab() { return (nghost+10); } 

每一次,如果使用的話,其運行時的消耗

int x() { 
int a; 
int nghost = 4; 
if(particlesFlag) { nghost = 5;} 
a=nghost*5; 
} 


int ab() { 
int nghost = 4; 
if(particlesFlag) { nghost = 5;} 
return (nghost+10); 

}

等。

也想想這個。

假設

#ifdef PARTICLES 
int nghost = 5 
int aghost = 5 
int bghost = 5 
int cghost = 5 
int dghost = 5 
int eghost = 5 
int fghost = 5 
#else 
int nghost = 4 
int aghost = 4 
int bghost = 4 
int cghost = 4 
int dghost = 4 
int eghost = 4 
int fghost = 4 
#endif 
+0

感謝您的答覆,但我有點困惑。在我給出的例子中,可以將第一個翻譯成'int nghost = 5'(如果定義了「PARTICLES」)。所以這兩個例子唯一的區別就是在代碼執行過程中是否執行'if ... else ...'語句,對嗎? – DilithiumMatrix 2013-02-08 18:51:34

+0

當你說if和else時,它是在運行時,哪裏是你的程序預計會很快。 。預處理是在你編譯的時候,甚至在它實時進行之前。 。 – 2013-02-08 18:52:59

+0

對,我明白了。我沒有得到的是爲什麼**訪問變量('nghost')在兩種情況下是不同的。即如何將int x(){int a = nghost * 5; }如果'nghost'是通過預處理器與代碼中定義的,那麼'會不同? – DilithiumMatrix 2013-02-08 18:56:20