awsqsh的专栏

Thinking...

如何写for循环 效率高

 

#include <iostream>
#include <windows.h>
using namespace std;

#define num 100000
int main()
{
    int i,j;
    int k[num];
    int *p,*q;
     unsigned long a = GetTickCount();

    for (i=0;i<num;i+=1)                         //据说这里每次都要计算 a*sizeof(int)
     
         k[i]=0;
          unsigned long b = GetTickCount()-a;
          printf("%ld\n",b);
          a = GetTickCount();
    for(p=k;p<k+num;p++)                  //据说这里要计算1*4    但是每次都是1*4 编译器可以优化。
     
         *p=0;
          b = GetTickCount()-a;
          printf("%ld\n",b);   
        
         system("pause");
         return 0;
}

//很明显上面的GetTickCount()函数无法计算出精确时间。在win 98下是55毫秒 win2000下是10ms

所以都会显示0;

 

如何获得更高精度??

#include <iostream>
#include <windows.h>
using namespace std;

#define num 500000
int main()
{
    int i,j;
    int k[num];
    int *p,*q;
     LARGE_INTEGER temp;
     LONGLONG t1,t2;
   
     double fMin,fFreq,fTim;
    
     QueryPerformanceCounter(&temp);
     fFreq = (double)temp.QuadPart;  //获得计数器时钟频率
     printf("fFreq:%lf\n",fFreq);
     t1 = temp.QuadPart;
    
         for (i=0;i<num;i+=1)
         {
             k[i]=0;
         }
         QueryPerformanceCounter(&temp);
         t2 = temp.QuadPart;
         fMin = (double)(t2-t1);
         fTim = fMin / fFreq;
         printf("%lf\n",fTim);


   
   
     
        for(p=k;p<k+num;p++)
        {
             *p=0;
        }
         QueryPerformanceCounter(&temp);
         t2 = temp.QuadPart;
         fMin = (double)(t2-t1);
         fTim = fMin / fFreq;
         printf("%lf\n",fTim);
        
         system("pause");
         return 0;
}
        
   /*
   LARGE_INTEGER t1,t2,feq;
      QueryPerformanceFrequency(&feq);//每秒跳动次数
      QueryPerformanceCounter(&t1);//测前跳动次数
      for(int i = 0;i<10000;i++);
      QueryPerformanceCounter(&t2);//测后跳动次数
      double d=((double)t2.QuadPart-(double)t1.QuadPart)/((double)feq.QuadPart);//时间差秒
      std::cout<<d<<std::endl;
   */

还是失败了,未完。。。待续

阅读更多
个人分类: C/C++
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭