gpt4 book ai didi

c++ - 我如何知道一个 STL 对象占用了多少内存?

转载 作者:IT老高 更新时间:2023-10-28 22:25:40 25 4
gpt4 key购买 nike

我需要在我的程序中收集有关内存使用情况的统计信息。

我的代码主要是使用 STL 编写的。

有什么方法可以知道 STL 对象消耗了多少内存?

例如,

string s1 = "hello";
string s2 = "hellohellohellohellohellohellohellohellohellohellohellohellohello";

s1s2 消耗了多少内存?显然 sizeof(string)+s1.length() 不太准确。

最佳答案

如果您愿意稍微打扰一下,您可以创建一个自定义分配器来按容器类型或按分配的类型跟踪所有堆使用情况。对于确定内存使用情况,这是非常侵入性的,但也非常准确。这不会跟踪堆本身占用多少内存,因为这高度依赖于操作系统。

template<class TrackType> 
size_t* mem_used() {static size_t s = 0; return &s;}

template<class T, class TrackType, class BaseAllocator = std::allocator<T> >
class TrackerAllocator : public BaseAllocator {
public:
typedef typename BaseAllocator::pointer pointer;
typedef typename BaseAllocator::size_type size_type;

TrackerAllocator() throw() : BaseAllocator() {}
TrackerAllocator(const TrackerAllocator& b) throw() : BaseAllocator(b) {}
TrackerAllocator(TrackerAllocator&& b) throw() : BaseAllocator(b) {}
template <class U> TrackerAllocator(const typename TrackerAllocator::template rebind<U>::other& b) throw() : BaseAllocator(b) {}
~TrackerAllocator() {}

template<class U> struct rebind {
typedef TrackerAllocator<U, TrackType, typename BaseAllocator::template rebind<U>::other> other;
};

pointer allocate(size_type n) {
pointer r = BaseAllocator::allocate(n);
*mem_used<TrackType>() += n;
return r;
}
pointer allocate(size_type n, pointer h) {
pointer r = BaseAllocator::allocate(n, h);
*mem_used<TrackType>() += n;
return r;
}
void deallocate(pointer p, size_type n) throw() {
BaseAllocator::deallocate(p, n);
*mem_used<TrackType>() -= n;
}
};

而用法是:

typedef std::basic_string<char, 
std::char_traits<char>,
TrackerAllocator<char, std::string> > trackstring;
typedef std::vector<int,
TrackerAllocator<int, std::vector<int> > > trackvector;
// ^ ^
// This identifies which memory to track
// it can be any type, related or no.
// All with the same type will be tracked togeather
int main() {
trackstring mystring1("HELLO WORLD");
std::cout << *mem_used<std::string>() << '\n'; //display memory usage of all strings

trackstring mystring2("MUCH LONGER STRING THAT DEFINITELY GETS HEAP ALLOCATED!");
std::cout << *mem_used<std::string>() << '\n'; //display memory usage of all strings

trackvector myvec(mystring1.begin(), mystring1.end());
std::cout << *mem_used<std::vector<int> >() << '\n'; //display memory usage of all vector<int>
// ^ ^
// This identifies which memory type from above to look up.
return 0;
}

Windows 结果:

0 //this is zero, because the string did not allocate heap space.
64
11

http://ideone.com/lr4I8 (GCC) 结果:

24
92
11

关于c++ - 我如何知道一个 STL 对象占用了多少内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7448514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com