42

我正在回答一个问题并推荐大型类型的按值返回,因为我确信编译器会执行返回值优化 (RVO)。但后来有人向我指出,Visual Studio 2013 没有在我的代码上执行 RVO。

我在这里发现了一个关于 Visual Studio 无法执行 RVO 的问题,但在这种情况下,结论似乎是,如果它真的很重要,Visual Studio 将执行 RVO。就我而言,这确实很重要,它对性能产生了重大影响,我已经通过分析结果确认了这一点。这是简化的代码:

#include <vector>
#include <numeric>
#include <iostream>

struct Foo {
  std::vector<double> v;
  Foo(std::vector<double> _v) : v(std::move(_v)) {}
};

Foo getBigFoo() {
  std::vector<double> v(1000000);
  std::iota(v.begin(), v.end(), 0);  // Fill vector with non-trivial data

  return Foo(std::move(v));  // Expecting RVO to happen here.
}

int main() {
  std::cout << "Press any key to start test...";
  std::cin.ignore();

  for (int i = 0; i != 100; ++i) {  // Repeat test to get meaningful profiler results
    auto foo = getBigFoo();
    std::cout << std::accumulate(foo.v.begin(), foo.v.end(), 0.0) << "\n";
  }
}

我期望编译器对来自getBigFoo(). 但它似乎是在复制Foo

我知道编译器将为Foo. 我也知道,与兼容的 C++11 编译器不同,Visual Studio 不会Foo. 但这应该没问题,RVO 是一个 C++98 概念,无需移动语义即可工作。

那么问题来了,Visual Studio 2013 在这种情况下不执行返回值优化是否有充分的理由呢?

我知道一些解决方法。我可以定义一个移动构造函数Foo

Foo(Foo&& in) : v(std::move(in.v)) {}

这很好,但是有很多遗留类型没有移动构造函数,很高兴知道我可以依赖 RVO 来处理这些类型。此外,某些类型可能本质上是可复制的,但不可移动。

如果我从 RVO 更改为 NVRO(称为返回值优化),那么 Visual Studio似乎确实执行了优化:

  Foo foo(std::move(v))
  return foo;

这很奇怪,因为我认为 NVRO不如RVO 可靠。

更奇怪的是,如果我更改它的构造函数,Foo它会创建并填充vector

  Foo(size_t num) : v(num) {
    std::iota(v.begin(), v.end(), 0);  // Fill vector with non-trivial data
  }

当我尝试做 RVO 时,而不是把它移进去,它可以工作:

Foo getBigFoo() {
  return Foo(1000000);
}

我很高兴采用其中一种解决方法,但我希望能够预测 RVO 将来何时会像这样失败,谢谢。

编辑: 来自@dyp 的更简洁的现场演示

Edit2:我为什么不直接写return v;

首先,它没有帮助。Profiler 结果表明,如果我只是编写,Visual Studio 2013 仍然会复制向量return v;,即使它确实有效,也只是一种解决方法。我并没有试图真正修复这段特定的代码,我试图理解 RVO 失败的原因,以便我可以预测它将来何时可能失败。确实,这是编写此特定示例的一种更简洁的方式,但是在很多情况下我不能只编写return v;.,例如,如果Foo有额外的构造函数参数。

4

1 回答 1

4

如果代码看起来应该优化,但没有得到优化,我会在这里提交错误http://connect.microsoft.com/VisualStudio或向 Microsoft 提出支持案例。这篇文章虽然是针对 VC++2005 的(我找不到当前版本的文档),但它确实解释了一些它不起作用的场景。http://msdn.microsoft.com/en-us/library/ms364057(v=vs.80).aspx#nrvo_cpp05_topic3

如果我们想确保优化已经发生,一种可能性是检查汇编输出。如果需要,这可以作为构建任务自动化。

这需要使用 /FAs 选项生成 .asm 输出,如下所示:

cl test.cpp /FAs

会生成test.asm。

下面是 PowerShell 中的一个潜在示例,可以通过这种方式使用:

PS C:\test> .\Get-RVO.ps1 C:\test\test.asm test.cpp
NOT RVO test.cpp - ; 13   :   return Foo(std::move(v));// Expecting RVO to happen here.

PS C:\test> .\Get-RVO.ps1 C:\test\test_v2.optimized.asm test.cpp
RVO OK test.cpp - ; 13   :   return {std::move(v)}; // Expecting RVO to happen here.

PS C:\test> 

剧本:

# Usage Get-RVO.ps1 <input.asm file> <name of CPP file you want to check>
# Example .\Get-RVO.ps1 C:\test\test.asm test.cpp
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
  [string]$assemblyFilename,

  [Parameter(Mandatory=$True,Position=2)]
  [string]$cppFilename
)

$sr=New-Object System.IO.StreamReader($assemblyFilename)
$IsInReturnSection=$false
$optimized=$true
$startLine=""
$inFile=$false

while (!$sr.EndOfStream)
{
    $line=$sr.ReadLine();

    # ignore any files that aren't our specified CPP file
    if ($line.StartsWith("; File"))
    {
        if ($line.EndsWith($cppFilename))
        {
            $inFile=$true
        }
        else
        {
            $inFile=$false
        }
    }

    # check if we are in code section for our CPP file...
    if ($inFile)
    {
        if ($line.StartsWith(";"))
        {
            # mark start of "return" code
            # assume optimized, unti proven otherwise
            if ($line.Contains("return"))
            {
                $startLine=$line 
                $IsInReturnSection=$true
                $optimized=$true
            }
        }

        if ($IsInReturnSection)
        {
            # call in return section, not RVO
            if ($line.Contains("call"))
            {
                $optimized=$false
            }

            # check if we reached end of return code section
            if ($line.StartsWith("$") -or $line.StartsWith("?"))
            {
                $IsInReturnSection=$false
                if ($optimized)
                {
                    "RVO OK $cppfileName - $startLine"
                }
                else
                {
                    "NOT RVO $cppfileName - $startLine"
                }
            }
        }
    }

}
于 2014-11-17T08:01:19.907 回答