【发布时间】:2009-10-06 14:17:34
【问题描述】:
我有问题.... 我在while循环中将数据写入数组。关键是我经常这样做。看来,这种写作现在是代码中的瓶颈。所以我认为这是由写入内存引起的。这个数组并不是很大(比如 300 个元素)。问题是可以这样做:仅在while循环完成后将其存储在缓存中并在内存中更新?
[编辑 - 复制自 Alex 添加的答案]
double* array1 = new double[1000000]; // this array has elements
unsigned long* array2 = unsigned long[300];
double varX,t,sum=0;
int iter=0,i=0;
while(i<=max_steps)
{
varX+=difX;
nm0 = int(varX);
if(nm1!=nm0)
{
array2[iter] = nm0; // if you comment this string application works more then 2 times faster :)
nm1=nm0;
t = array1[nm0]; // if you comment this string , there is almost no change in time
++iter;
}
sum+=t;
++i;
}
首先,我要感谢大家的回答。确实,不输入代码有点愚蠢。所以我决定现在就去做。
double* array1 = new double[1000000]; // this array has elements
unsigned long* array2 = unsigned long[300];
double varX,t,sum=0;
int iter=0,i=0;
while(i<=max_steps)
{
varX+=difX;
nm0 = int(varX);
if(nm1!=nm0)
{
array2[iter] = nm0; // if you comment this string application works more then 2 times faster :)
nm1=nm0;
t = array1[nm0]; // if you comment this string , there is almost no change in time
++iter;
}
sum+=t;
++i;
}
原来如此。如果有人有任何想法,那就太好了。再次非常感谢。
真诚的 亚历克斯
【问题讨论】:
-
"If you comment this string[...]" 那么,让应用程序运行速度快两倍也可能是由于编译器优化了条件块(取决于编译器和后面的代码) ) 因为它不再做任何有意义的事情了。
-
在这个问题发生 9 年后,这似乎很快就会成为可能,至少在一些运行 Linux 内核 4.19 的 Intel CPU 上:kernelnewbies.org/Linux_4.19#Intel_Cache_Pseudo-locking。更多信息events.linuxfoundation.org/wp-content/uploads/2017/11/…