在某些情况下,为什么std :: allocator的性能要比Linux上的自定义分配器好得多?

时间:2019-06-15 03:51:39

标签: c++ linux performance allocator

研究与STL一起使用的自定义分配器时,我发现在某些情况下std :: allocator的性能明显优于我在某些Linux平台上尝试过的任何自定义分配器。

在Windows上,同时使用VC ++ 2019和clang,我看不到任何明显的速度差异。

我无法理解的是为什么我会在Linux平台上看到这些截然不同的结果(我已经尝试过Fedora和Ubuntu。)我创建了一个程序来演示我所看到的内容(借用在单独引用的问题中提出的SampleAllocator)在代码中。)

#include <vector>
#include <chrono>
#include <iostream>

// SimpleAllocator code from:
// https://stackoverflow.com/questions/22487267/unable-to-use-custom-allocator-with-allocate-shared-make-shared
template <class Tp>
struct SimpleAllocator
{
  typedef Tp value_type;
  SimpleAllocator() {}
  template <class T> SimpleAllocator(const SimpleAllocator<T>& other) {}
  Tp* allocate(std::size_t n) { return static_cast<Tp*>(::operator new(n * sizeof(Tp))); }
  void deallocate(Tp* p, std::size_t n) { ::operator delete(p); }
};
template <class T, class U>
bool operator==(const SimpleAllocator<T>&, const SimpleAllocator<U>&) { return true; }
template <class T, class U>
bool operator!=(const SimpleAllocator<T>&, const SimpleAllocator<U>&) { return false; }

template <typename T> void TimeInsertions(T &vec, const std::string &alloc_name)
{
    auto start_time = std::chrono::steady_clock::now();
    for (int i = 0 ; i<=100000000; i++)
    {
        vec.push_back(i);
    }
    auto end_time = std::chrono::steady_clock::now();

    std::cout << "Time using " << alloc_name << ": "
              << std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count()
              << "ms" << std::endl;
}

int main()
{
    {
        std::vector<int, SimpleAllocator<int>> vec;
        TimeInsertions(vec, "SampleAllocator");
    }

    {
        std::vector<int> vec;
        TimeInsertions(vec, "std::allocator");
    }
}

鉴于此基本示例,我希望看到引用的SimpleAllocator与std :: allocator的性能大致相同,但实际上看到的是这样的结果:

$ ./sample
Time using SampleAllocator: 5283ms
Time using std::allococator: 1485ms

当然,这些结果因计算机而异,但是在不同的Linux机器上,我得到的结果也非常相似。这使我相信g ++或Linux中有一些我不完全了解的魔术。谁能提供任何见解来帮助我理解我所看到的?

编辑

回到今天,也许这可能与编译器优化有关。我使用gcc的-O3标志在Linux上重新编译了代码,结果却截然不同(更接近):

$ ./sample
Time using SampleAllocator: 341ms
Time using std::allocator: 479ms

因此,也许这仅与STL代码的编译方式有关,而与特定平台的优化无关。

0 个答案:

没有答案
相关问题