gpt4 book ai didi

c++ - 在 Visual Studio 2010 中使用 'auto' 关键字的性能损失

转载 作者:IT老高 更新时间:2023-10-28 12:43:08 26 4
gpt4 key购买 nike

使用新的 auto 关键字降低了我的代码执行时间。我将问题缩小到以下简单的代码片段:

#include <iostream>
#include <map>
#include <vector>
#include <deque>
#include <time.h>

using namespace std;

void func1(map<int, vector<deque<float>>>& m)
{
vector<deque<float>>& v = m[1];
}

void func2(map<int, vector<deque<float>>>& m)
{
auto v = m[1];
}

void main () {

map<int, vector<deque<float>>> m;
m[1].push_back(deque<float>(1000,1));

clock_t begin=clock();
for(int i = 0; i < 100000; ++i) func1(m);
cout << "100000 x func1: " << (((double)(clock() - begin))/CLOCKS_PER_SEC) << " sec." << endl;

begin=clock();
for(int i = 0; i < 100000; ++i) func2(m);
cout << "100000 x func2: " << (((double)(clock() - begin))/CLOCKS_PER_SEC) << " sec." << endl;

}

我在 i7/Win7 机器( Release模式;VS2010)上得到的输出是:

100000 x func1: 0.001 sec.
100000 x func2: 3.484 sec.

谁能解释为什么使用 auto 会导致执行时间如此不同?

显然,有一个简单的解决方法,即完全停止使用 auto,但我希望有更好的方法来解决这个问题。

最佳答案

您正在将 vector 复制到 v

试试这个来创建引用

auto& v = ...

关于c++ - 在 Visual Studio 2010 中使用 'auto' 关键字的性能损失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8485719/

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