简单的循环效率问题

  1、减少不必要的循环层数。

  例如,求股票 n日ma值。

  在最内层每次循环n次求和求平均。其实这层的循环可以省略。

 1     for(int j=0;j<4;j++)
 2     {
 3         for(int i=0;i<lStockTotal*1000;i++)
 4         {    
 5             sum0=0;
 6             if(i<day[j]-1)
 7             {
 8                 (*(pt_Ma+i)).ma[j]=0;
 9             }
10             else
11             {
12                 for(int k=i-day[j]+1;k<=i;k++)
13                 {
14                     sum0+=(*(pt_Stock_test+k)).m_lClosePrice;
15                 }
16                 (*(pt_Ma+i)).ma[j]=sum0/day[j];
17             }
18         }
19 
20     }
View Code

   去除最内层循环后,代码如下:

 1     for(int j=0;j<4;j++)
 2     {
 3         for(int i=0;i<lStockTotal*1000;i++)
 4         {    
 5             sum[j]+=(*(pt_Stock_test+i)).m_lClosePrice;
 6             if(i<day[j]-1)
 7             {                
 8                 (*(pt_Ma+i)).ma[j]=0;
 9             }
10             else if(i==day[j]-1)
11             {                
12                 (*(pt_Ma+i)).ma[j]=sum[j]/day[j];
13             }
14             else if(i>day[j]-1)
15             {
16                 sum[j]-=(*(pt_Stock_test-day[j]+i)).m_lClosePrice;                
17                 (*(pt_Ma+i)).ma[j]=sum[j]/day[j];
18             }
19         }
20 
21     }
View Code

 

 2、多重循环 把循环次数少的放外层

下面 是效率不高的代码。

 1     for(int i=0;i<lStockTotal*1000;i++)
 2     {    
 3         for(int j=0;j<4;j++)
 4         {
 5             sum[j]+=(*(pt_Stock_test+i)).m_lClosePrice;
 6             if(i<day[j]-1)
 7             {                
 8                 (*(pt_Ma+i)).ma[j]=0;
 9             }
10             else if(i==day[j]-1)
11             {                
12                 (*(pt_Ma+i)).ma[j]=sum[j]/day[j];
13             }
14             else if(i>day[j]-1)
15             {
16                 sum[j]-=(*(pt_Stock_test-day[j]+i)).m_lClosePrice;                
17                 (*(pt_Ma+i)).ma[j]=sum[j]/day[j];
18             }
19         }
20 
21     }
View Code

 

最后发下我的测试结果,注:*1000是我做测试用的。

从上到下 代码执行所用的时间  

1.4680000000000000  

0.21900000000000000

0.28100000000000003

 

 

posted on 2013-06-26 18:23  黑色圣光  阅读(250)  评论(0编辑  收藏  举报