【问题标题】:High CPU usage on using boost::pool使用 boost::pool 时 CPU 使用率高
【发布时间】:2019-03-06 07:17:57
【问题描述】:

我尝试使用boost::pool 来减少内存分配的 CPU 消耗,但 profiling 测试代码结果不如预期。 这是测试代码。

ma​​in1.cpp

#include "pool_singleton.h"

int main()
{
    const int size = 400000;
    for (int i = 0; i < 100000; ++i)
    {
        auto obj = pNew uint8_t[size]; // use singleton_pool

        pDelete(obj, size);
    }
    return 0;
}

ma​​in2.cpp

#include "pool_singleton.h"

int main()
{
    const int size = 400000;
    for (int i = 0; i < 100000; ++i)
    {
        auto obj = new uint8_t[size];

        delete[] obj;
    }

    return 0;
}

pool_singleton.h

#pragma once

#include <iostream>
#include <memory>

// boost
#include <boost/pool/singleton_pool.hpp>

struct pNewTag{};
typedef boost::singleton_pool<pNewTag, 1> pool;

inline void* operator new (size_t size, int num)
{
    auto ptr = pool::ordered_malloc(size);
    return ptr;
}

template<int N>
struct memMan
{
    static memMan<N> x;
    inline static void delete_ptr(void *p, size_t size)
    {
        pool::free(p, size);
    }

    static inline void pool_destroy()
    {
        pool::purge_memory();
    }

};

template<int N>
memMan<N> memMan<N>::x;

#define pNew new(1)
#define pDelete(p, size) memMan<0>::delete_ptr(p, size)
#define purge memMan<0>::pool_destroy()

ma​​in1.cpp 的 CPU 使用率是 ma​​in2.cpp 的两倍。
我预计 ma​​in1.cpp 的 CPU 使用率会随着时间的推移而下降,但直到最后它仍然很高。 问题是

  1. 我的 singleton_pool 使用有误吗?
  2. 有没有办法减少singleton_pool的cpu消耗?
  3. 还有其他减少内存分配的 CPU 消耗的想法吗?

【问题讨论】:

  • 为什么是ordered_malloc?你为什么输出 i ?写入标准输出会影响您的基准。
  • I expected that the CPU usage of main2.cpp will drop as time passes, but it remained high until the end 你的意思是 main1 吗?
  • 我使用ordered_malloc 来分配数组。有没有办法不使用ordered_malloc?输出 i 只是检查语句。我忘记抹掉了。 main1.cpp 的 CPU 负载高于 main2.cpp 的结果没有改变。
  • I expected that the CPU usage of main2.cpp will drop as time passes, but it remained high until the end do you mean main1 ? 是的。感谢您指出这一点。
  • 您为什么希望 CPU 使用率下降?为什么 CPU 不能尽可能快地完成工作?为什么 CPU 的运行速度会比它能够运行的速度慢,在这两种情况下,你已经给它做了大量的工作,而没有任何东西可以阻止它完成这些工作?

标签: c++ boost memory-management


【解决方案1】:

您正在考虑错误的 CPU 使用率。如果 CPU 使用率低于 100%,则意味着 CPU 上的资源正在被浪费。如果 CPU 使用率为 100%,则表示 CPU 正在以最快的速度前进。

在所有其他条件相同的情况下,对于基本上只是要求 CPU 完成工作的任务,CPU 使用率越高越好,因为这意味着工作会尽快完成。只要有工作要做,CPU 就会全速运行,除非由于某些原因(例如必须等待 I/O 或过热)而无法运行——这些都是坏事。

相反,测量工作的总 CPU 消耗。更高效的代码将需要更少的 CPU 来完成等效的工作。

我预计 main1.cpp 的 CPU 使用率会随着时间的推移而下降,但直到最后它仍然很高。

太棒了。这意味着 CPU 会尽可能快地完成工作,直到完成所有工作。当 CPU 仍有工作要做时,任何低于 100% 的下降都表明效率低下,导致 CPU 无法尽快完成工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-09
    • 2014-07-16
    • 2014-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多