【问题标题】:How to defer computation in C++ until needed?如何将 C++ 中的计算推迟到需要时?
【发布时间】:2021-01-02 15:43:25
【问题描述】:

在 C++(*) 中,是否有可能有一个结构“推迟”一些计算直到需要(如果不需要,可能永远不会进行计算)?我的用例如下:我有大约十几个布尔变量,每个变量都是通过一些函数调用计算的。之后,有一个相当长(且复杂)的条件语句,它使用这些布尔变量以不同的组合来确定代码接下来将采取的操作。

这是一些人为的示例代码,希望能更好地说明我在做什么:

bool const b1 = func1(param1,param2,param3);
bool const b2 = func2(param4);
// ...
bool const b15 = func15(param35,param36,param37,param38);

if (b1 && !b5 && (b2 || b3)) { do_something1(); }
else if (b3 && !b15 || (b4 && b9 && b6)) { do_something2(); }
else if (b14 || b10 || (!b11 && b7)) { do_something3(); }
else if (b8) {
    if (!b1 || !b6) { do_something4(); }
    else if ( /* ... */ ) // ... etc
}
// ... and on and on

这纯粹是一个人为的例子,但希望它能说明这个想法。

很明显,这段代码可以在没有布尔值的情况下重新编写,并且在大条件语句中直接调用函数。但我觉得这会使本来就不容易阅读的代码更难阅读,更容易出错。而且这种逻辑可能会改变,所以我觉得从重构的角度来看,布尔值也更容易管理。

此外,任何 bool 都可能在条件中被多次引用;所以直接使用函数意味着可以重复执行。 (我在想 std::bind 可能会从可读性的角度让我到达那里;但它仍然可能会多次调用任何 funcN() 调用。)

我正在寻找的是两个词中最好的,比如“延迟”计算。如果不是在代码开头显式计算和分配,我可以说,“只根据需要评估这些(并记住结果)”。大的条件语句是这样的,一般来说,并不是所有的布尔值都需要计算来确定接下来会发生什么。这里的目标是提高性能,因为此代码经常被调用。所以我试图减少每次迭代的工作量。

(*) 最好是 C++14(或更早版本),因为这是我的雇主正在使用的。

编辑:这样的事情怎么样:

#include <iostream>
#include <functional>

//////////////////////////////////////////////////////////////////////////////
class Sum
{
    public:
        int sum(int const a, int const b) { ++n_calls_; return (a+b); }
        int getNCalls() const { return n_calls_; }

    private:
        int n_calls_ = 0;
};

//////////////////////////////////////////////////////////////////////////////
template <class BoundFunc, typename RetType>
class DeferredCompute
{
    public:
        DeferredCompute(BoundFunc const& f) : func_(f) { }

        RetType operator()()
        {
            if (!computed_)
            {
                value_ = func_();
                computed_ = true;
            }
            return value_;
        }

    private:
        bool             computed_ = false;
        RetType          value_;
        BoundFunc const& func_;
};

//////////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    Sum s;
    auto boundSum = std::bind(&Sum::sum, &s, 75, 25);

    DeferredCompute<decltype(boundSum), int> deferredSum(boundSum);

    // call function directly repeatedly
    for (int i=0; i<5; ++i)
    {
      std::cout << "boundSum()=" << boundSum() << std::endl;
    }
    std::cout << "s.getNCalls()=" << s.getNCalls() << std::endl;

    // should only call once
    for (int i=0; i<5; ++i)
    {
      std::cout << "deferredSum()=" << deferredSum() << std::endl;
    }
    std::cout << "s.getNCalls()=" << s.getNCalls() << std::endl;

    return 0;
}

输出:

boundSum()=100
boundSum()=100
boundSum()=100
boundSum()=100
boundSum()=100
s.getNCalls()=5
deferredSum()=100
deferredSum()=100
deferredSum()=100
deferredSum()=100
deferredSum()=100
s.getNCalls()=6

【问题讨论】:

  • 在deferred 模式下尝试std::async
  • 您的库的核心 C++ 语言中没有任何东西可以做到这一点。但是实现看起来完全一样的东西并不太复杂,假装是bool,行为像bool,但在第一次引用它时调用一个函数,并在所有函数上使用先前评估的结果后续参考。
  • “是否有可能有一个结构“推迟”一些计算直到需要?是的。如果您对其进行编程,或使用提供它的库。
  • 相关(虽然有点旧,但仍然相关):stackoverflow.com/questions/414243/lazy-evaluation-in-c

标签: c++ performance deferred-execution


【解决方案1】:

带有选项 std::launch::deferred 的 std::async 是您正在寻找的。​​p>

https://en.cppreference.com/w/cpp/thread/async

例如

auto future = std::async(std::launch::deferred, [](){return 5;});
// future isn't calculated yet

auto result = future.get();
// result = 5, and will remain cached while in scope.

【讨论】:

  • 我不确定这是否适用于我的情况,请参阅std::async and lambda function in C++ gives no associated state。具体来说,“你不能在同一个未来调用get() 两次”。我对the get() documentation 的理解是,在第一次调用get() 之后,未来是无效的。根据我的例子,任何布尔值都可以是被多次引用,暗示了多个 future.get() 调用。
  • @Matt 所以你想要的不是如何推迟计算;因为无论如何这就是函数所做的 - 但是如何缓存函数的结果,以便您只执行一次计算。他们不是同一个问题。
【解决方案2】:

首先,我会尝试使用一些 lambda 闭包。

const auto b1 = [&]() { return func1(param1,param2,param3); };
const auto b2 = [&]() { return func2(param4); };
// ...
const auto b15 = [&]() { return func15(param35,param36,param37,param38); };

if (b1() && !b5() && (b2() || b3())) { do_something1(); }
...

如果您需要缓存布尔结果而不是整个 程序的生命周期(静态),这个解决方案可以 实现它(三个级别的 lambda 闭包;它是“Inception”)。

/**
  g++ -std=c++17 -o prog_cpp prog_cpp.cpp \
      -pedantic -Wall -Wextra -Wconversion -Wno-sign-conversion \
      -g -O0 -UNDEBUG -fsanitize=address,undefined
**/

#include <iostream>

void
test(int i)
{
  auto cache=[](auto expr)
    {
      return [expr, res=false, done=false]() mutable
        {
          if(!done) { res=expr(); done=true; }
          return res;
        };
    };
  auto b1=cache([&]() { std::cout << "(eval b1)"; return i>2; });
  auto b2=cache([&]() { std::cout << "(eval b2)"; return i<5; });
  std::cout << "1: b1=" << b1() << "  b2=" << b2() << '\n';
  std::cout << "2: b1=" << b1() << "  b2=" << b2() << '\n';
}

int
main()
{
  for(int i=0; i<6; ++i)
  {
    std::cout << "~~~~~~~~\n";
    test(i);
  }
  return 0;
}
/**
~~~~~~~~
1: b1=(eval b1)0  b2=(eval b2)1
2: b1=0  b2=1
~~~~~~~~
1: b1=(eval b1)0  b2=(eval b2)1
2: b1=0  b2=1
~~~~~~~~
1: b1=(eval b1)0  b2=(eval b2)1
2: b1=0  b2=1
~~~~~~~~
1: b1=(eval b1)1  b2=(eval b2)1
2: b1=1  b2=1
~~~~~~~~
1: b1=(eval b1)1  b2=(eval b2)1
2: b1=1  b2=1
~~~~~~~~
1: b1=(eval b1)1  b2=(eval b2)0
2: b1=1  b2=0
**/

【讨论】:

  • 如果没有记忆/缓存,你最终会在每次需要 bool 时重新运行它们。如果你要走这条路,我会用一个重载的int() 运算符创建一个包装类,它只会在后台调用一次函数。
【解决方案3】:

为了可读性和可维护性,您可以将程序组织为状态机。这为您提供了将状态转换和动作彼此分离的好处,而且如果需要,以后重新连接逻辑应该相当简单。

这里有一些例子: C++ code for state machine

【讨论】:

    【解决方案4】:

    如果不是在代码开头显式计算和分配,我可以说,“只根据需要评估这些(并记住结果)”

    /// @brief only evaluate these as needed (and remember the result)
    class lazy final
    {
        mutable std::future<bool> value_;
    public:
        template<typename Functor>
        lazy(Functor &&f)
        : value_{ std::async(std::launch::deferred,
                             std::forward<Functor>(f)) }
        {
        }
    
        operator bool() const
        {
             return value_.get();
        }
    };
    

    客户端代码:

    auto b1 = lazy::lazy{[&]{ return func1(param1,param2,param3); }};
    auto b2 = lazy::lazy{[&]{ return func2(param4); }};
    // ...
    bool const b15 = lazy::lazy{[&]{ return func15(param35,param36,param37,param38); }};
    
    // rest remains the same as your contrieved example
    

    我还没有编译这段代码。如果在 c++14 中工作(正如你提到的),你可能需要一个类似于这样的工厂函数:

    template<typename Functor>
    auto make_lazy(Functor&& f) { return lazy<Functor>(std::forward<Functor>(f)); }
    

    唯一改变的是 bX 变量的声明。您还可以考虑添加代码,告诉您在实践中调用每个惰性求值的频率,首先声明这些 bX 变量,然后立即并行启动它们,而不是以延迟的方式启动它们。但只有在你以两种方式衡量性能后才这样做。

    【讨论】:

      猜你喜欢
      • 2016-12-25
      • 1970-01-01
      • 2023-03-18
      • 2012-11-14
      • 2014-10-01
      • 2016-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多