小编Ada*_*ora的帖子

优化for循环的函数调用

我有一些简单的功能

int f_0(int);
int f_1(int);
...
int f_n(int);
Run Code Online (Sandbox Code Playgroud)

然后我有一些for循环,我调用f_i(),这个循环中的条件不必相同

for (int i = 0; i < n; i++) {
   ...
   if (condition) {
      int myInt = f_i(); // this is not real implementation but shows the result
                         // I want to achieve
      ... //edit
   }
...
}
Run Code Online (Sandbox Code Playgroud)

以下是我尝试实现此方法的方法:

  • 分解for循环并在相应的部分中调用每个函数.这导致最快的代码,但这是非常不优雅的,并且这样的代码很难进一步开发.
  • 指向功能的指针

    typedef int (*Foo) (int);

    Foo fptr[] = { f_0, f_1, ... , f_n };

这是一种优雅的方法,但在我的情况下,它比分解循环慢4.4.函数的常量指针产生类似的结果.

  • 将我的功能封装到开关功能中.这比打破循环慢2.6.

有没有更好的方法来实现这个?理想的解决方案是具有紧凑代码的解决方案,但编译器会分解循环并让计算最快.

我正在使用MSVC 2012并在发布模式下运行,并将优化设置为最大化速度.

编辑:

这是我的测试代码:

head.h

namespace c {
const int w = …
Run Code Online (Sandbox Code Playgroud)

c++ optimization for-loop function

5
推荐指数
1
解决办法
3239
查看次数

奇怪的构造函数调用

我有一个类在构造函数中完成所有工作(它在那里构造,运行一些计算,输出它们,然后它在构造函数中被破坏所有这些).

这是简化的代码:

#include <iostream>

class myInt {
public:
    myInt(int init) : mInt(init) {}

    int mInt;
};

class SinglePara {
public:
    SinglePara(myInt first) : member(first.mInt) { std::cout << member << std::endl; this->~SinglePara(); }

    int member;
};

class TwoPara {
public:
    TwoPara(myInt first, myInt second) : member1(first.mInt), member2(second.mInt) { std::cout << member1 + member2 << std::endl; this->~TwoPara(); }

    int member1, member2;
};

int main()
{
    myInt one(1), two(2), three(3);
    TwoPara myTwo(one, two);      // outputs 3 as expected
    TwoPara(one, two);            // outputs 3 …
Run Code Online (Sandbox Code Playgroud)

c++ constructor

1
推荐指数
1
解决办法
92
查看次数

标签 统计

c++ ×2

constructor ×1

for-loop ×1

function ×1

optimization ×1