增加堆栈大小以使用alloca()?

mez*_*hic 4 c c++ memory performance memory-management

这是两个重叠的问题 - 我希望为大型数组尝试alloca(),而不是在堆上分配动态大小的数组.这样我就可以在不进行堆分配的情况下提高性能.但是,我得到的印象堆栈大小通常都很小?增加堆栈的大小是否有任何缺点,以便我可以充分利用alloca()?是我拥有的内存越多,我可以按比例增加堆栈大小吗?

EDIT1:最好是Linux

EDIT2:我没有考虑到指定的尺寸 - 我宁愿知道如何判断限制/界限是什么.

Bil*_*eal 10

在大多数unix-y平台上,堆栈大小(默认情况下)为8MB,在Windows上为1MB(即,因为Windows具有从堆栈问题中恢复的确定性方法,而unix-y平台通常会抛出通用SIGSEGV信号).

如果您的分配很大,那么在堆上分配与在堆栈上分配之间不会有太大的性能差异.当然,每个分配的堆栈效率稍高,但如果您的分配很大,分配的数量可能很小.

如果你想要一个更大的类似堆栈的结构,你总是可以编写自己的allocator,它从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
}
Run Code Online (Sandbox Code Playgroud)