性能测试 程序输出:
1:temp = array[i]*i: 2430.0 ms
2:temp = GET(array,i) *i: 2430.0 ms
3:temp = get(array,i)*i: 2840.0 ms
4:int a = get(array,i);temp = a*i: 3370.0 ms
5:int a = array[i];temp = a*i;: 2010.0 ms
6:temp = *(array+i)*i: 2430.0 ms
7:temp = *(array+i)*i: 2010.0 ms
其中,GET是宏定义,get是函数。
显然,1,2,6是一样的,符合预期。(当然有时不一样,但很接近)
3 通过函数调用来访问,时间长点,符合预期。
4 在3的基础上,还多了次赋值,时间长电,符合预期。
5和7 就不可思议了,她在1的基础上错了次赋值,时间竟然变短了。
测试代码
#include <stdlib.h> #include <stdio.h> #include <iostream> using namespace std; #define GET(array,index) array[index] int get(int *array,int index) { return array[index]; } int main(void) { clock_t start,stop; float elapsedTime; int rounds = 10000; int array_size = 100000; int *array = new int[array_size]; for(int i=0;i<array_size;i++) { array[i]=i; } int temp = 0; start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { temp = array[i]*i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "1:temp = array[i]*i: %3.1f ms\n", elapsedTime ); start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { temp = GET(array,i) *i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "2:temp = GET(array,i) *i: %3.1f ms\n", elapsedTime ); start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { temp = get(array,i)*i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "3:temp = get(array,i)*i: %3.1f ms\n", elapsedTime ); start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { int a = get(array,i); temp = a*i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "4:int a = get(array,i);temp = a*i: %3.1f ms\n", elapsedTime ); start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { int a = array[i]; temp = a*i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "5:int a = array[i];temp = a*i;: %3.1f ms\n", elapsedTime ); start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { temp = *(array+i)*i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "6:temp = *(array+i)*i: %3.1f ms\n", elapsedTime ); start = clock(); for(int round=0;round<rounds;round++) { for(int i=0;i<array_size;i++) { int a = *(array+i); temp = a*i; } } stop= clock(); elapsedTime = (float)(stop - start) / (float)CLOCKS_PER_SEC * 1000.0f; printf( "7:temp = *(array+i)*i: %3.1f ms\n", elapsedTime ); return 0; }
发现貌似是乘以i的原因导致那个奇怪的问题,
把乘以i改为乘以1或者2之类的,貌似就不会的。
但是如果是乘以i+1的话还是很不符合预期。
看来要看一下汇编代码。
原文地址:http://blog.csdn.net/lingerlanlan/article/details/24653715