我負責兩個程序,這是第二個。第一個程序沒有計算()函數,並且在程序啓動和結束時計時。我的電腦將顯示從.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;
}
只是出於好奇,你的系統最大堆棧幀大小是什麼?你在那個函數中有幾乎24KB的雙數組。這是一個雙倍的loooooot :) – Manu343726
你在計算時間時會包括印刷線,這可能會花費大部分時間,所以即使其他問題已經解決,時間可能仍然不會有太大變化。測量時間時只應考慮主要計算 –