循环加快——C++

来源:互联网 发布:万睿科技有限公司 知乎 编辑:程序博客网 时间:2024/05/07 04:46

#ifndef LOCALVARIABLES_H_
#define LOCALVARIABLES_H_

#include <iostream>
#include <ctime>

const int N = 10000000;

class A
{
public:
 int getValue()
 {
  return a;
 }
private:
 int a;
};

class TestTime
{
public:
 void test();
 clock_t test1();
 clock_t test2();
 clock_t test3();
private:
 clock_t duration1;
 clock_t duration2;
 clock_t duration3;
};
#endif

 

#include "localVariables.h"


void TestTime::test()
{
 clock_t d1 = test1();
 clock_t d2 = test2();
 clock_t d3 = test3();

 std::cout<<"duration1 = "<<d1<<"ms // 变量定义在for循环里面"<<std::endl
  <<"duration2 = "<<d2<<"ms // 变量定义在for循环外面,且采用达夫编程技巧"<<std::endl
  <<"duration3 = "<<d3<<"ms // 变量定义在for循环外面"<<std::endl;
}
clock_t TestTime::test1()
{
 clock_t begin1,end1;
 begin1 = clock();
 for ( int i=0; i<N; ++i )
 {
  A a;  //编译器会自动优化,定义在外面或者里面效果一样
  int b = a.getValue();
 }
 end1 = clock();
 duration1 = end1 - begin1;
 return duration1;
}

clock_t TestTime::test2()
{
 A a;
 int b;
 int N2 = N/10;
 clock_t begin2,end2;
 begin2 = clock();
 //达夫编程技巧降低循环判断次数
 for ( int i=0; i<N2; ++i )
 {
  b = a.getValue();//1
  b = a.getValue();
  b = a.getValue();//3
  b = a.getValue();
  b = a.getValue();//5
  b = a.getValue();
  b = a.getValue();//7
  b = a.getValue();//8
  b = a.getValue();//9
  b = a.getValue();//10
 }
 end2 = clock();
 duration2 = end2 - begin2;
 return duration2;
}

clock_t TestTime::test3()
{
 A a;
 clock_t begin3,end3;
 begin3 = clock();
 for ( int i=0; i<N; ++i )
 {
  int b = a.getValue();
 }
 end3 = clock();
 duration3 = end3 - begin3;
 return duration3;
}

 

#include "localVariables.h"
//using namespace std; //尽量少用,降低编译时间

void main()
{
 TestTime tt;
 tt.test();

 system("pause");
}

 

输出:

duration1 = 249ms // 变量定义在for循环里面
duration2 = 234ms // 变量定义在for循环外面,且采用达夫编程技巧
duration3 = 250ms // 变量定义在for循环外面
请按任意键继续. . .

 


 

0 0