我一直认为这std::vector是"作为阵列实施的一般智慧",等等等等等等.今天我去了测试它,似乎不是这样:
这是一些测试结果:
UseArray completed in 2.619 seconds
UseVector completed in 9.284 seconds
UseVectorPushBack completed in 14.669 seconds
The whole thing completed in 26.591 seconds
Run Code Online (Sandbox Code Playgroud)
这大约慢了3-4倍!没有真正证明" vector可能会慢几纳米"的评论.
我使用的代码:
#include <cstdlib>
#include <vector>
#include <iostream>
#include <string>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/microsec_time_clock.hpp>
class TestTimer
{
public:
TestTimer(const std::string & name) : name(name),
start(boost::date_time::microsec_clock<boost::posix_time::ptime>::local_time())
{
}
~TestTimer()
{
using namespace std;
using namespace boost;
posix_time::ptime now(date_time::microsec_clock<posix_time::ptime>::local_time());
posix_time::time_duration d = now - start;
cout << name << " completed in " << …Run Code Online (Sandbox Code Playgroud) 在我们的C++课程中,他们建议不再在新项目中使用C++数组.据我所知,Stroustroup本人建议不要使用数组.但是有显着的性能差异吗?
已经广泛讨论了C++向量和普通数组之间的性能差异,例如这里和这里.通常讨论的结论是,当使用[]运算符访问并且编译器启用内联函数时,向量和数组在性能方面类似.这就是预期的原因,但我遇到的情况似乎并非如此.以下几行的功能非常简单:采用3D体积并交换并应用某种3D小面具一定次数.根据VERSION宏的不同,卷将被声明为向量,并通过atoperator(VERSION=2)访问,声明为向量并通过[](VERSION=1)访问或声明为简单数组.
#include <vector>
#define NX 100
#define NY 100
#define NZ 100
#define H 1
#define C0 1.5f
#define C1 0.25f
#define T 3000
#if !defined(VERSION) || VERSION > 2 || VERSION < 0
#error "Bad version"
#endif
#if VERSION == 2
#define AT(_a_,_b_) (_a_.at(_b_))
typedef std::vector<float> Field;
#endif
#if VERSION == 1
#define AT(_a_,_b_) (_a_[_b_])
typedef std::vector<float> Field;
#endif
#if VERSION == 0 …Run Code Online (Sandbox Code Playgroud)