使用如下程序测试对数组元素的访问速度:#include <stdio.h>
#include <windows.h>int main(int argc, char* argv[])
{
unsigned long t1,t2,t3;
int a[65536]={0},l,k = 0; do{
t1 =  GetTickCount(); for(int i = 0 ; i < 65535; i ++)
for(int j = 0 ; j < 65535 ; j ++)
l = a[1];
t2 = GetTickCount(); for(i = 0 ; i < 65535; i ++)
for(int j = 0 ; j < 65535 ; j ++)
l = a[65535];
t3 = GetTickCount(); printf("Access a[1] time = %ld\n",t2-t1);
printf("Access a[65535] time = %ld\n\n",t3-t2);
}while(++k < 100); return 0;
}在VC++ 6上的结果是:访问a[1]比访问a[65535]的速度快3-4倍。在VC++.NET上对两者的访问速度没有明显差别。那么,为什么会这样呢?为什么访问速度会有差异? 在VC++ 6调试模式下打开反汇编窗口, 看到l = a[1]和l=a[65535]的代码差不多,都是:
mov         edx,dword ptr [ebp-xxxxh]   // 两者仅仅是这里的xxxx不同
mov         dword ptr [ebp-40010h],edx奇怪!

解决方案 »

  1.   

    这段程序在我的P4 2.0G 512M RAM的机器上运行结果如下:Access a[1] time = 13500
    Access a[65535] time = 47844Access a[1] time = 13140
    Access a[65535] time = 48032Access a[1] time = 13172
    Access a[65535] time = 47828Access a[1] time = 13156
    Access a[65535] time = 48141// 开了点其它比较消耗cpu load的程序,两个时间均增长,并且差距倍数拉大。
    Access a[1] time = 20015
    Access a[65535] time = 97766Access a[1] time = 23797
    Access a[65535] time = 103093Access a[1] time = 26750
    Access a[65535] time = 98063Access a[1] time = 15937
    Access a[65535] time = 50485Access a[1] time = 13953
    Access a[65535] time = 52859Access a[1] time = 14172
    Access a[65535] time = 53266Access a[1] time = 14047
    Access a[65535] time = 53484Access a[1] time = 14641
    Access a[65535] time = 56343Access a[1] time = 15125
    Access a[65535] time = 55329Access a[1] time = 14812
    Access a[65535] time = 55516Access a[1] time = 15187
    Access a[65535] time = 57110Access a[1] time = 15906
    Access a[65535] time = 55172Access a[1] time = 15031
    Access a[65535] time = 54531Access a[1] time = 14000
    Access a[65535] time = 52922Access a[1] time = 14391
    Access a[65535] time = 54828
      

  2.   

    我想是内存开辟的原因吧,vc6可能是一部分一部分的开辟,依次提交那些地址,所以访问a[65535]要更慢些——因为访问它,要等到它的内存地址被提交! 而vc7可能就是同时提交那么大的内存快,所以就不会有速度的差异了! 这个并不是“你数到1 和数到65535哪个需要时间多些?”——因为如果同时都提交到内存了的话,a[1]和a[65535]的寻址,并不会有什么很大区别的,毕竟cpu寻址a[65535]并不是挨个搜寻过去,而是直接跳到a[65535]地址上的!          
      

  3.   

    现在更奇怪了,在我同事的机器(PIII 733 1G RAM)上,把数组改小一些,比如,65530,两者运行的时间就基本差不多一样了。在我的机器上,两者仍然差很多。
      

  4.   

    a[65536]改成a[65535]之後:Access a[1] time = 10000
    Access a[65535] time = 10562之前:Access a[1] time = 9688
    Access a[65535] time = 10500應該和內存分配有關吧,不是太了解,關注我的機器 CPU 2.8G   RAM 512
      

  5.   

    我的机器上为什么运行不起来,只要运行CPU就占用100%,且没有结果输出??