gpt4 book ai didi

c++ - std::move() 作为性能瓶颈?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:14:35 26 4
gpt4 key购买 nike

我有一个自定义环形缓冲区实现,它使用通过 new [] 分配的普通数组,然后使用 std::move 将元素 move 到数组中。这是我的 push() 方法的实现:

void push(value_type&& value)
{
_content[_end] = std::move(value); // 9.2% of execution is spend here
increment(); // 0.6% here
}

我 move 到数组中的对象基本上只是一个指针和一个std::unique_ptr:

struct Task
{
Task()
{}

Function function;
Batch *batch;
};

函数看起来像这样:

class Function
{
public:
template<typename F>
Function(F&& f) :
_implementation(new ImplementationType<F>(std::move(f)))
{}

void operator() () { _implementation->Call(); }

Function() = default;
Function(Function&& other) :
_implementation(std::move(other._implementation))
{}

Function& operator=(Function&& other)
{
_implementation = std::move(other._implementation);
return *this;
}

Function(const Function&) = delete;
Function(Function&) = delete;
Function& operator= (const Function&) = delete;

private:
struct Base
{
virtual void Call() = 0;
virtual ~Base() {}
};

template<typename F>
struct ImplementationType : Base
{
ImplementationType(F&& f) :
function(std::move(f))
{}

void Call()
{
function();
}

F function;
};

std::unique_ptr<Base> _implementation;
};

我在循环中重复调用 ringbuffers push() 方法来用任务填充缓冲区,那里没有其他计算发生。我希望 std::move() 的开销很小,而且绝对不会占用我计算时间的大部分。谁能指出我在这里做错的正确方向?

最佳答案

std::move 本身在运行时什么都不做;它只是将其参数转换为适合传递给 move 赋值运算符的右值。这是一项需要时间的任务。

如果 _content[_end] 不为空,则重新分配唯一指针将删除旧对象。也许这就是花时间的原因?

关于c++ - std::move() 作为性能瓶颈?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19499655/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com