我一直认为,这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 大约慢了3到4倍!对于“ vector可能会慢一些纳秒”的注释,并没有真正的理由。
和我使用的代码:
#include #include
#include #include
#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_clockboost::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 " << d.total_milliseconds() / 1000.0 <<
" seconds" << endl;
}
private:
std::string name;
boost::posix_time::ptime start;
};
struct Pixel { Pixel() { }
Pixel(unsigned char r, unsigned char g, unsigned char b) : r(r), g(g), b(b)
{
}
unsigned char r, g, b;
};
void UseVector() { TestTimer t("UseVector");
for(int i = 0; i < 1000; ++i)
{
int dimension = 999;
std::vector<Pixel> pixels;
pixels.resize(dimension * dimension);
for(int i = 0; i < dimension * dimension; ++i)
{
pixels[i].r = 255;
pixels[i].g = 0;
pixels[i].b = 0;
}
}
}
void UseVectorPushBack() { TestTimer t("UseVectorPushBack");
for(int i = 0; i < 1000; ++i)
{
int dimension = 999;
std::vector<Pixel> pixels;
pixels.reserve(dimension * dimension);
for(int i = 0; i < dimension * dimension; ++i)
pixels.push_back(Pixel(255, 0, 0));
}
}
void UseArray() { TestTimer t("UseArray");
for(int i = 0; i < 1000; ++i)
{
int dimension = 999;
Pixel * pixels = (Pixel *)malloc(sizeof(Pixel) * dimension * dimension);
for(int i = 0 ; i < dimension * dimension; ++i)
{
pixels[i].r = 255;
pixels[i].g = 0;
pixels[i].b = 0;
}
free(pixels);
}
}
int main() { TestTimer t1("The whole thing");
UseArray();
UseVector();
UseVectorPushBack();
return 0;
} 我做错了什么吗?还是我刚刚打破了这个表演神话?
我在Visual Studio 2005中使用发布模式。
在Visual C ++中,#define _SECURE_SCL 0减少UseVector一半(将其减少到4秒)。IMO,这确实是巨大的。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
使用以下内容:
g ++ -O3 Time.cpp -I ./a.out UseArray 在2.196秒 内完成UseVector 在4.412秒内完成UseVectorPushBack 在8.017秒内完成 整个事情在14.626秒内完成
因此数组的速度是向量的两倍。
但是,在更详细地查看了代码之后,这是可以预期的。当您在向量上运行两次,而数组仅运行一次。注意:当您resize()使用向量时,您不仅要分配内存,还要遍历向量并在每个成员上调用构造函数。
稍微重新安排代码,以便向量仅初始化每个对象一次:
std::vector pixels(dimensions * dimensions, Pixel(255,0,0)); 现在再次执行相同的计时:
g ++ -O3 Time.cpp -I ./a.out UseVector在2.216秒内完成
向量现在的性能仅比阵列稍差。IMO的这种差异微不足道,可能是由与测试无关的一堆东西引起的。
我还要考虑到您没有正确初始化/销毁方法中的Pixel对象,UseArrray()因为没有调用构造函数/析构函数(对于这个简单的类,这可能不是问题,但是稍微复杂一点的(例如,使用指针或成员)带有指针)会引起问题。 问题来源于stack overflow