2013-12-21 21 views
0

我負責兩個程序,這是第二個。第一個程序沒有計算()函數,並且在程序啓動和結束時計時。我的電腦將顯示從.523秒到.601秒的任何內容。C++用於數組乘法的內聯函數10000

第二項任務是爲計算創建一個內聯函數,我相信我做錯了,因爲它不是更快。我不確定我是否將計算函數設置爲正確的,因爲它包含顯示信息,或者內聯函數應該只關注乘法。無論哪種方式將數組拉出主體並進入函數不會更快。

編譯器是否忽略了它?

#include <ctime> 
#include <iostream> 
using namespace std; 

    inline int calculation(){ 
    int i; 
    double result[10000]; 

double user[10000]; 
    for(i=0; i<10000; i++){ 
     user[i]=i+100;  
    } 

    double second[10000]; 
    for(i=0; i<10000; i++){ 
     second[i]=10099-i;  
    } 

    for (i = 0; i < 10000; i++){ 
     result[i] = user[i] * second[i]; 
    } 

    for (i = 0; i < 10000; i++){ 
     cout << user[i] << " * " << second[i] << " = " << result[i] << '\n'; 
     } 
    } 


    int main() { 

    time_t t1 = time(0);     // get time now 
    struct tm * now = localtime(& t1); 
    cout << "The time now is: "; 
    cout << now->tm_hour << ":" << now->tm_min << ":" << now->tm_sec << endl; 

    clock_t t;      // get ticks 
    t = clock(); 
    cout << " Also calculating ticks...\n"<<endl; 

    calculation();     // inline function 

    time_t t2 = time(0);     // get time now 
    struct tm * now2 = localtime(& t2); 
    cout << "The time now is: "; 
    cout << now2->tm_hour << ":" << now2->tm_min << ":" << now2->tm_sec << endl; 
    time_t t3= t2-t1; 

    cout << "This took me "<< t3 << " second(s)" << endl; // ticks 
    t = clock() - t; 
    float p; 
    p = (float)t/CLOCKS_PER_SEC; 
    cout << "Or more accuratley, this took " << t << " clicks" 
    << " or " << p << " seconds"<<endl; 

    } 
+0

只是出於好奇,你的系統最大堆棧幀大小是什麼?你在那個函數中有幾乎24KB的雙數組。這是一個雙倍的loooooot :) – Manu343726

+0

你在計算時間時會包括印刷線,這可能會花費大部分時間,所以即使其他問題已經解決,時間可能仍然不會有太大變化。測量時間時只應考慮主要計算 –

回答

1

編譯器是否忽略了它?

很可能,是的。這可能是因爲兩個原因:

  • 您正在以調試模式編譯。在調試模式下,所有inline關鍵字都將被忽略以便於調試。
  • 它忽略它,因爲函數對於內聯函數來說太長了,並且使用了太多的堆棧空間來安全地內聯,並且只調用一次。 inline關鍵字是編譯器提示,不是強制性要求。程序員的方式建議編譯器內聯函數,就像在釋放模式下的編譯器經常內聯函數以提高性能一樣。如果它只看到負值,它將不符合。

此外,由於單一調用,不管是否有效,甚至可能會看到差異。 CPU上的單個本地函數調用比操作系統級別的單個任務切換更容易。

0

您應該禁用優化以驗證您的操作是否有任何效果,因爲編譯器很有可能已經自己內聯函數。另外,如果您想確切知道代碼的功能,您應該使用g ++中的-s標誌進行編譯,然後查看編譯器爲您的程序生成的程序集。這將消除關於編譯器對您的程序做什麼的所有不確定性。

0

我不會使函數內聯並將數組定義爲靜態。例如

int calculation(){ 
    int i; 
    static double result[10000]; 

static double user[10000]; 
    for(i=0; i<10000; i++){ 
     user[i]=i+100;  
    } 

    static double second[10000]; 
    for(i=0; i<10000; i++){ 
     second[i]=10099-i;  
    } 

    for (i = 0; i < 10000; i++){ 
     result[i] = user[i] * second[i]; 
    } 

    for (i = 0; i < 10000; i++){ 
     cout << user[i] << " * " << second[i] << " = " << result[i] << '\n'; 
     } 
    } 
+0

您沒有在其源代碼中找到滾動條 - 調用僅低於默認高度。 –

+0

@Niels Keurentjes,是的,你說得對。所以我改變了我的帖子。 –