0
点赞
收藏
分享

微信扫一扫

假定循环内用时较多,fun1比fun2快多少


运行环境:WinXP VS2005(VC8)


#include <iostream>

using namespace std ;

#include <time.h>


#define WAN (10000)

const int iNum = WAN*300;

void fun1(int* p)

{

for( int i = 0 ; i < iNum ; i++ )

{

p[i] = i;



}

}


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 Test()

{

int * p = new int[iNum];

long x1 = clock();

fun1(p);

long x2 = clock();

fun2(p);

long x3 = clock();

cout << (x2-x1) << "豪秒 " << (x3-x2) << "豪秒" << endl;

delete [] p ;

}


void main()

{

Test();

Test();

Test();

Test();

Test();

}

循环次数(iNum )由3亿改到300万次,fun1快约16毫秒。约快50%

47豪秒 31豪秒

47豪秒 31豪秒

47豪秒 31豪秒

47豪秒 31豪秒

47豪秒 31豪秒

把fun1,fun2的用时改多些

#include <iostream>

using namespace std ;

#include <time.h>

#include <math.h>


#define WAN (10000)

const int iNum = WAN*300;

#define NN(n) (pow((float)n,100))


void fun1(int* p)

{

for( int i = 0 ; i < iNum ; i++ )

{

p[i] = NN(i);



}

}


void fun2(int* p)

{

for( int i = 0 ; i < iNum ; i+= 4 )

{

p[i] = NN(i);

p[i+1] = NN(i+1);

p[i+2] = NN(i+2);

p[i+3] = NN(i+3) ;

}

}


void Test()

{

int * p = new int[iNum];

long x1 = clock();

fun1(p);

long x2 = clock();

fun2(p);

long x3 = clock();

cout << (x2-x1) << "豪秒 " << (x3-x2) << "豪秒" << endl;

delete [] p ;

}


void main()

{

Test();

Test();

Test();

Test();

Test();

}

11781豪秒 12203豪秒

11922豪秒 11921豪秒

12219豪秒 11688豪秒

11625豪秒 11641豪秒

11703豪秒 11734豪秒

结论:用时基本相同

举报

相关推荐

0 条评论