我的代碼如下:優化元件的總和在陣列
double a,b; //These variable are inputs to the function
double *inArr; //This is also an iput to the function whose size is NumElements
double *arr = new double[numElements]; //NumElements is ~ 10^6
double sum = 0.0;
for(unsigned int i=0;i<numElements;++i)
{
double k = a*inArr[i] + b; //This doesn't take any time
double el = arr[i]; //This doesn't take any time
el *= k; //This doesn't take any time
sum += el; //This takes a long time!!!
}
此代碼越過每個時間計算的值k,對於每個元件它增加了k次該元素來總結數組的元素。我將代碼分成了很多步驟,以便當我的分析器告訴我哪一行需要很長時間時,我將確切知道哪個計算是罪魁禍首。我的配置文件告訴我,將el加總是什麼會減慢我的程序速度(這看起來有點奇怪,簡單的加法會很慢,但我稱這個函數爲數百次,每次執行數百萬次計算)。我唯一的理論是,因爲總和在不同的範圍,使用它的操作需要更長的時間。所以我編輯的代碼是:
double a,b; //These variable are inputs to the function
double *inArr; //This is also an iput to the function whose size is NumElements
double *arr = new double[numElements]; //NumElements is ~ 10^6
double sum = 0.0;
for(unsigned int i=0;i<numElements;++i)
{
double k = a*inArr[i] + b; //This doesn't take any time
double el = arr[i]; //This doesn't take any time
el *= k; //This doesn't take any time
double temp = sum + el; //This doesn't take any time
sum = el; //This takes a long time!!!
}
現在sum操作花費很少的時間,即使它訪問sum變量。這項任務現在需要很長時間。我的理論是否正確,發生這種情況的原因是分配給不在當前範圍內的變量需要更長的時間?如果是這樣,爲什麼這是真的?有什麼辦法可以快速完成這項任務嗎?我知道我可以使用並行化來優化這個,我想知道我是否可以順序地做得更好。我使用VS 2012以發行模式運行,我使用VS性能分析器作爲分析器。
編輯:
一旦我刪除了原來的訪問inArr是什麼是最耗時的優化。
你爲什麼不使用'std :: accumulate(std :: begin(arr),std :: end(arr),0.0,[](auto sum,auto elem){return sum + elem * someQuickCaclc();});'?這應該會給你高度優化的代碼。 – TemplateRex
您是否嘗試禁用優化(/ O1,/ O2)標誌?這可以模仿一些分析。 –
*您認爲每條迭代所需的時間*「很長時間」*多長時間?飛秒?小時?天? – Roddy