在c ++中优化循环 [英] Optimizing for loop in c++

查看:81
本文介绍了在c ++中优化循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨专家,



i有2个for循环

Hi Experts,

i have two for loop

   for(y = Height; y--)
      {
        for(x = Width; x--)
         {
           im->setData(x, y, Getdata(x,y));
         }

      }

//definition for get and set data is as below

  T Getdata(unsigned int x, unsigned int y) const
   {
      return _Data[x * y];
   }
	
   void SetData(unsigned int x, unsigned int y, T data)
   {
      _Data[x + _width * y] = data;
   }





i希望进一步优化它,有人可以帮我进一步......



我尝试了什么:



i读取某些地方(int j = Num; j--)比(int j = 0; j



i want to optimize it further ,can somebody help me further...

What I have tried:

i read some where for(int j=Num;j--) is more efficient then for(int j=0;j

推荐答案

更有效率有两种可能的一般优化:

There are two possible general optimisations:


  1. 用必要的代码替换函数调用,
  2. 预先计算中间结果。



结果代码可能看起来像这样:


The resulting code may look like this:

int z = Width * (Height - 1);
for (y = Height - 1; y >= 0; y--, z-= Width)
{
    for (x = Width - 1; x >= 0; x--)
    {
        dest[x + z] = src[x * y];
    }
}


如果我是你,我会让代码工作和保持一致,然后再搞好优化任何东西。例如,Set和Gets不访问相同的对象。一旦你这样做(如果 _Data 是一个类似于thingy的数组)如何使用 std :: copy 来实际做副本?如果那还不够快,T是POD看看使用 std :: memcpy



但修复你的代码首先否则它会快速和错误。
If I were you I'd get the code working and consistent before messing about with optimising anything. Your Set and Gets don't access the same objects for example. Once you do that (and if _Data is an array like thingy) how about using std::copy to actually do the copy? If that's not fast enough and T is a POD look at using std::memcpy.

But fix your code first otherwise it'll be fast and wrong.


这篇关于在c ++中优化循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆