我想对(自定义)单链接列表中的元素运行一组操作。遍历链表并运行操作的代码很简单,但重复性很强,如果到处复制/粘贴,可能会出错。性能和仔细的内存分配在我的程序中很重要,因此我想避免不必要的开销。

我想编写一个包装程序以包含重复的代码并封装将在链表的每个元素上进行的操作。由于该操作中发生的功能各不相同,因此我需要捕获必须提供给该操作的多个变量(在实际代码中),因此我使用std::function进行了研究。在此示例代码中完成的实际计算在这里没有意义。

#include <iostream>
#include <memory>

struct Foo
{
  explicit Foo(int num) : variable(num) {}
  int variable;
  std::unique_ptr<Foo> next;
};

void doStuff(Foo& foo, std::function<void(Foo&)> operation)
{
  Foo* fooPtr = &foo;
  do
  {
    operation(*fooPtr);
  } while (fooPtr->next && (fooPtr = fooPtr->next.get()));
}

int main(int argc, char** argv)
{
  int val = 7;
  Foo first(4);
  first.next = std::make_unique<Foo>(5);
  first.next->next = std::make_unique<Foo>(6);
#ifdef USE_FUNC
  for (long i = 0; i < 100000000; ++i)
  {
    doStuff(first, [&](Foo& foo){ foo.variable += val + i; /*Other, more complex functionality here */ });
  }
  doStuff(first, [&](Foo& foo){ std::cout << foo.variable << std::endl; /*Other, more complex and different functionality here */ });
#else
  for (long i = 0; i < 100000000; ++i)
  {
    Foo* fooPtr = &first;
    do
    {
      fooPtr->variable += val + i;
    } while (fooPtr->next && (fooPtr = fooPtr->next.get()));
  }
  Foo* fooPtr = &first;
  do
  {
    std::cout << fooPtr->variable << std::endl;
  } while (fooPtr->next && (fooPtr = fooPtr->next.get()));
#endif
}

如果运行为:
g++ test.cpp -O3 -Wall -o mytest && time ./mytest
1587459716
1587459717
1587459718

real    0m0.252s
user    0m0.250s
sys 0m0.001s

而如果运行为:
g++ test.cpp -O3 -Wall -DUSE_FUNC -o mytest && time ./mytest
1587459716
1587459717
1587459718

real    0m0.834s
user    0m0.831s
sys 0m0.001s

这些计时在多次运行中相当一致,并且在使用std::function时显示4倍乘数。有什么更好的办法可以做我想做的事吗?

最佳答案

使用模板:

template<typename T>
void doStuff(Foo& foo, T const& operation)

对我来说,这给出了:
mvine@xxx:~/mikeytemp$ g++ test.cpp -O3 -DUSE_FUNC -std=c++14 -Wall -o mytest && time ./mytest
1587459716
1587459717
1587459718

real    0m0.534s
user    0m0.529s
sys     0m0.005s
mvine@xxx:~/mikeytemp$ g++ test.cpp -O3 -std=c++14 -Wall -o mytest && time ./mytest
1587459716
1587459717
1587459718

real    0m0.583s
user    0m0.583s
sys     0m0.000s

关于c++ - 避免std::function的开销,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55865079/

10-10 21:38
查看更多