内存分配、多线程和各种分配大小的性能

问题描述 投票:0回答:0

我写了一个应用程序,每秒需要创建数百万个对象。我发现内存分配对性能有很大的影响。因此我考虑编写自己的内存分配,但我不知道这是否有意义。 我的第一步是看看在多线程和不同大小中分配内存时发生了什么。

我的代码:

#include <array>
#include <chrono>
#include <iostream>
#include <omp.h>

int64_t timestamp() {
    return std::chrono::duration_cast<std::chrono::nanoseconds>          (std::chrono::system_clock::now().time_since_epoch()).count();
}

int main()
{
    static std::array<int, 6> threadcnt = { 1,2,4,8,16,32 };
    static std::array<int, 9> memsize = { 4,8,16,32,64,128,256,512,1024 };

    std::cout << std::fixed << std::setw(8) << "B/T";
    for (int tc : threadcnt) std::cout << std::fixed << std::setw(8) << tc;
    std::cout << std::endl;

    for (int ms : memsize) {
        std::cout << std::fixed << std::setw(8) << ms;

        for (int tc : threadcnt) {
            omp_set_num_threads(tc);

            int64_t start = timestamp();
#pragma omp parallel for
            for (int i = 0; i < 1000000; ++i) new char[ms];
            int64_t end = timestamp();

            float s = float(end - start) / 1000000000.;
            std::cout << std::fixed << std::setw(8) << std::setprecision(4) << s;
        }
        std::cout << std::endl;
    }
    return 0;
}

对于 threadcnt = { 1,2,4,8,16,32 } 和 memsize = { 4,8,16,32,64,128,256,512,1024 } 的每个组合,执行一百万次分配。

使用 Visual C++ 编译并在 Windows 11 下运行它会在几秒钟内给出以下结果(CPU:16Core/32Threads):

 B/T       1       2       4       8      16      32
   4  0.0241  0.0129  0.0094  0.0041  0.0054  0.0063
   8  0.0256  0.0128  0.0070  0.0041  0.0049  0.0063
  16  0.0294  0.0152  0.0082  0.0055  0.0078  0.0091
  32  0.0333  0.0181  0.0101  0.0071  0.0108  0.0124
  64  0.0412  0.0233  0.0133  0.0105  0.0171  0.0183
 128  0.0584  0.0337  0.0204  0.0167  0.0267  0.0276
 256  0.0789  0.0469  0.0302  0.0347  0.0494  0.0479
 512  0.1229  0.0792  0.0566  0.0614  0.0972  0.0936
1024  0.2176  0.1508  0.1122  0.1105  0.1919  0.1842

最多 8 个线程性能提高,但随后出现故障。为什么会这样? Windows 是否存在为多个线程分配内存的问题?

更重要的是:为什么 dows 的时间消耗会随着分配大小的增加而急剧增加?如果内存会被初始化,我可以理解这一点,但事实并非如此。

有人可以解决这个问题吗?提前致谢!

c++ multithreading memory-management openmp
© www.soinside.com 2019 - 2024. All rights reserved.