我分析了 C++ vector 和 C 风格数组之间的性能。结果有点出乎意料,因为文献说 vector 的性能应该非常接近原始数组,但事实并非如此。我在分析中做错了什么吗?
void getVector1(int n)
{
if (n < 0)
{
throw std::invalid_argument(std::string("negative argument n:") + std::to_string(n));
}
auto tp1 = std::chrono::steady_clock::now();
std::vector<int> ivec(n);
int i = 0;
for (auto& x : ivec)
{
x = ++i;
}
auto tp2 = std::chrono::steady_clock::now();
std::chrono::duration<double, std::micro> dd = tp2 - tp1;
printf("spend %6.2f us time to create: %d elements vector inside %s() at %s:%d \n", dd.count(), n, __func__, __FILE__, __LINE__);
}
void getVector2(int n)
{
if (n < 0)
{
throw std::invalid_argument(std::string("negative argument n:") + std::to_string(n));
}
auto tp1 = std::chrono::steady_clock::now();
auto pvec = new int[n];
for (int i = 0; i < n; ++i)
{
pvec[i] = i;
}
auto tp2 = std::chrono::steady_clock::now();
std::chrono::duration<double, std::micro> dd = tp2 - tp1;
delete[] pvec;
printf("spend %6.2f us time to create: %d elements vector inside %s() at %s:%d \n", dd.count(), n, __func__, __FILE__, __LINE__);
}
int main()
{
int n = 10000000;
getVector1(n);
getVector2(n);
return 0;
}
代码是使用带有 -O3 选项的 g++ 编译的。
花费 11946.38 us 时间创建:在 testVectorSpeed.cpp 中的 getVector1() 中有 10000000 个元素 vector
花费 7298.66 us 时间创建:在 getVector2() 中的 10000000 个元素 vector 在 testVectorSpeed.cpp
最佳答案
此成本归结为 vector 通过其分配器将内存归零。
首先,使用像 google benchmark 这样的基准测试库总是一个好主意。而不是推出自己的基准测试。我们可以使用 quick-bench.com快速使用图书馆。重写您的代码以使用它:
// Just the benchmark code:
void getVector1(benchmark::State& state)
{
int n = state.range(0);
for (auto _ : state) {
std::vector<int> ivec(n);
// This is the same operation that you are doing
std::iota(ivec.begin(), ivec.end(), 1);
// We don't want the compiler to see that we aren't
// using `ivec` and thus optimize away the entire
// loop body
benchmark::DoNotOptimize(ivec);
}
}
void getArray1(benchmark::State& state)
{
int n = state.range(0);
for (auto _ : state) {
auto pvec = new int[n];
std::iota(pvec, pvec + n, 1);
benchmark::DoNotOptimize(pvec);
delete[] pvec;
}
}
// Smaller number still reproduces it
BENCHMARK(getVector1)->Arg(10000);
BENCHMARK(getArray1)->Arg(10000);
Click on image for quick-bench link
通过稍微尝试一下,我们可以发现成本差异只是用std::uninitialized_fill 清零内存的成本。 (on quick-bench)。
确实,如果我们改用 an allocator that leaves the memory uninitialized ,两者之间没有可衡量的区别:
// Allocator from https://stackoverflow.com/a/41049640
template <typename T, typename A = std::allocator<T>>
class default_init_allocator : public A {
typedef std::allocator_traits<A> a_t;
public:
// http://en.cppreference.com/w/cpp/language/using_declaration
using A::A; // Inherit constructors from A
template <typename U> struct rebind {
using other =
default_init_allocator
< U, typename a_t::template rebind_alloc<U> >;
};
template <typename U>
void construct(U* ptr)
noexcept(std::is_nothrow_default_constructible<U>::value) {
::new(static_cast<void*>(ptr)) U;
}
template <typename U, typename...Args>
void construct(U* ptr, Args&&... args) {
a_t::construct(static_cast<A&>(*this),
ptr, std::forward<Args>(args)...);
}
};
void getVector1(benchmark::State& state)
{
int n = state.range(0);
for (auto _ : state) {
std::vector<int, default_init_allocator<int>> ivec(n);
std::iota(ivec.begin(), ivec.end(), 1);
benchmark::DoNotOptimize(ivec);
}
}
void getArray1(benchmark::State& state)
{
int n = state.range(0);
for (auto _ : state) {
auto pvec = new int[n];
std::iota(pvec, pvec + n, 1);
benchmark::DoNotOptimize(pvec);
delete[] pvec;
}
}
BENCHMARK(getVector1)->Arg(10000);
BENCHMARK(getArray1)->Arg(10000);
关于c++ - vector 和原始 C 风格数组之间的性能比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50454117/
我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代
我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby数组,我们在StackOverflow上找到一
我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]
我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此
我有一个围绕一些对象的包装类,我想将这些对象用作散列中的键。包装对象和解包装对象应映射到相同的键。一个简单的例子是这样的:classAattr_reader:xdefinitialize(inner)@inner=innerenddefx;@inner.x;enddef==(other)@inner.x==other.xendenda=A.new(o)#oisjustanyobjectthatallowso.xb=A.new(o)h={a=>5}ph[a]#5ph[b]#nil,shouldbe5ph[o]#nil,shouldbe5我试过==、===、eq?并散列所有无济于事。
我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server
我正在使用puppet为ruby程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这
这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我正在尝试在Ruby中制作一个cli应用程序,它接受一个给定的数组,然后将其显示为一个列表,我可以使用箭头键浏览它。我觉得我已经在Ruby中看到一个库已经这样做了,但我记不起它的名字了。我正在尝试对soundcloud2000中的代码进行逆向工程做类似的事情,但他的代码与SoundcloudAPI的使用紧密耦合。我知道cursesgem,我正在考虑更抽象的东西。广告有没有人见过可以做到这一点的库或一些概念证明的Ruby代码可以做到这一点? 最佳答案 我不知道这是否是您正在寻找的,但也许您可以使用我的想法。由于我没有关于您要完成的工作