运行环境:WinXP VS2005(VC8)
核心代码:
#include <iostream> using namespace std ; #include <time.h> #define WAN (10000) const int iNum = WAN*WAN*3; void fun2(int* p) { for( int i = 0 ; i < iNum ; i+= 4 ) { p[i] = i; p[i+1] = i+1; p[i+2] = i+2; p[i+3] = i+3 ; } } void fun3(int* p) { for( int i = 0 ; i < iNum ; i+= 8 ) { p[i] = i; p[i+1] = i+1; p[i+2] = i+2; p[i+3] = i+3 ; p[i+4] = i+4 ; p[i+5] = i+5 ; p[i+6] = i+6 ; p[i+7] = i+7 ; } }
测试程序一:
void main() { int * p = new int[iNum]; int x1 = time(NULL); fun2(p); int x2 = time(NULL); fun3(p); int x3 = time(NULL); cout << (long)(x2-x1) << "秒 " << (long)(x3-x2) << "秒"; delete [] p ; }
五次的运行结果:
4,3
3,3
3,3
4,2
3,3
测试程序三(fun3在前,fun2在后):
2,3
2,4
2,3
3,3
2,3
总的来说fun3 比fun2快,但平均不到1秒。