这是两个重叠的问题-我希望对大型数组尝试alloca(),而不是在堆上分配动态大小的数组。这是为了在不进行堆分配的情况下提高性能。然而,我得到的印象堆叠大小通常是相当小的?为了充分利用alloca(),增加堆栈的大小有什么缺点吗?我拥有的RAM越多,我可以按比例增加堆栈大小?
EDIT1:最好是Linux
EDIT2:我的脑海中没有一个特定的大小-我更愿意知道如何判断是什么决定了限制/边界。
发布于 2013-03-26 07:33:04
堆栈大小(默认情况下)在大多数unix-y平台上为8MB,在Windows上为1MB (也就是说,因为Windows有a deterministic way for recovering from out of stack problems,而unix-y平台通常会抛出通用的SIGSEGV信号)。
如果您的分配很大,那么在堆上分配和在堆栈上分配之间不会有太大的性能差异。当然,每次分配堆栈的效率会稍微高一些,但如果您的分配量很大,那么分配的数量可能会很少。
如果你想要一个更大的类似堆栈的结构,你可以编写自己的分配器,它从malloc获得一个大块,然后以类似堆栈的方式处理分配/释放。
#include <stdexcept>
#include <cstddef>
class StackLikeAllocator
{
std::size_t usedSize;
std::size_t maximumSize;
void *memory;
public:
StackLikeAllocator(std::size_t backingSize)
{
memory = new char[backingSize];
usedSize = 0;
maximumSize = backingSize;
}
~StackLikeAllocator()
{
delete[] memory;
}
void * Allocate(std::size_t desiredSize)
{
// You would have to make sure alignment was correct for your
// platform (Exercise to the reader)
std::size_t newUsedSize = usedSize + desiredSize;
if (newUsedSize > maximumSize)
{
throw std::bad_alloc("Exceeded maximum size for this allocator.");
}
void* result = static_cast<void*>(static_cast<char*>(memory) + usedSize);
usedSize = newUsedSize;
return result;
}
// If you need to support deallocation then modifying this shouldn't be
// too difficult
}发布于 2013-03-26 07:35:03
程序的主线程获得的默认堆栈大小是编译器特定的(和/或操作系统特定的),您应该查看相应的文档以了解如何扩大堆栈。
可能发生的情况是,您可能无法将程序的默认堆栈扩大到任意大小。
但是,正如前面所指出的,您可能能够在运行时创建一个具有所需堆栈大小的线程。
在任何情况下,与曾经分配的大缓冲区相比,alloca()没有太多好处。您不需要多次释放和重新分配它。
发布于 2013-03-26 07:49:07
alloca()和new / malloc()之间最重要的区别是,当您从当前函数返回时,使用alloca()分配的所有内存都将用完。
alloca()仅对小型临时数据结构有用。
它只对小数据结构有用,因为大数据结构将破坏堆栈的缓存局部性,这将给您带来相当大的性能影响。对于作为局部变量的数组也是如此。
只有在非常特殊的情况下才使用alloca()。如果不确定,请不要使用它。
一般规则是:不要将大数据结构(>= 1k)放在堆栈上。堆栈不能扩展。这是一种非常有限的资源。
https://stackoverflow.com/questions/15626737
复制相似问题