循环加快——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循环外面
请按任意键继续. . .
- 循环加快——C++
- 【C#】—循环语句
- C#——for循环
- C#——for循环
- 加快LOOP嵌套循环的一个方法
- 数据结构C#——循环链表
- C#——while循环语句
- C#——循环的中断
- C语言——分支与循环
- C#——while循环语句
- c#——循环的中断
- C语言基础——循环结构
- 数据结构——循环队列(c++)
- C语言——循环缓冲区
- C语言复习——循环结构
- C语言数据结构——循环队列
- c语言—循环结构编程实例
- Linux C 数据结构—-循环链表
- android4.0 x86 裁剪与定制
- 五、CCNode
- 图像处理中各种边缘检测的微分算子简单比较(Sobel,Robert, Prewitt,Laplacian,Canny)
- Oracle 递归查询 Connect by prior
- 创意:Soap一款新型的触摸式家用智能路由器
- 循环加快——C++
- java实现基于javapns1.6的ios服务器推送
- 软件调试之堆和堆检查
- 秋叶喻死亡,是用诗来
- 四、CCSprite
- 日常小技巧
- 数据结构学习5——顺序表查找
- 代码中犯过的几个小错误
- spring源码下载