1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
// Copyright 2019, The Macaulay2 team.
#ifndef __myalloc_hpp_
#define __myalloc_hpp_
#include <iostream>
// This class is static as it appears easiest if all allocator objects
// are essentially identical. It could be a static member of StatsAllocator,
// but then each type T would have a different stats object.
//
// This class is meant for debugging/benchmark use only.
// This class is not thread safe.
//
// TODO: perhaps include mathicgb logging facility, or perhaps even boost.
// However, this is much simpler for the moment.
class AllocLogger
{
public:
static size_t mNumAllocs;
static size_t mAllocSize;
static size_t mNumDeallocs;
static long mCurrentAllocSize;
static size_t mHighWater;
static void reset() {
mNumAllocs = 0;
mAllocSize = 0;
mNumDeallocs = 0;
mCurrentAllocSize = 0;
mHighWater = 0;
}
static void logAlloc(size_t num, size_t sz)
{
++AllocLogger::mNumAllocs;
AllocLogger::mAllocSize += num * sz;
AllocLogger::mCurrentAllocSize += num * sz;
if (AllocLogger::mCurrentAllocSize > AllocLogger::mHighWater)
AllocLogger::mHighWater = AllocLogger::mCurrentAllocSize;
// std::cout << "allocating " << num << " elements, each of size " << sz << std::endl;
}
static void logDealloc(size_t num, size_t sz)
{
++AllocLogger::mNumDeallocs;
AllocLogger::mCurrentAllocSize -= num * sz;
// std::cout << "deallocating " << num << " elements, each of size " << sz << std::endl;
}
};
std::ostream& operator<<(std::ostream& o, AllocLogger a);
/* The following code is adapted from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 2nd edition, 2012.
*/
template <typename T>
class StatsAllocator {
public:
typedef T value_type;
StatsAllocator() noexcept {}
template <typename U>
StatsAllocator(const StatsAllocator<U>&) noexcept {}
T* allocate(size_t num)
{
AllocLogger::logAlloc(num, sizeof(T));
return static_cast<T*>(::operator new (num * sizeof(T)));
}
void deallocate(T* p, std::size_t num)
{
AllocLogger::logDealloc(num, sizeof(T));
::operator delete(p);
}
};
// all specializations of this allocator are interchangeable
template <class T1, class T2>
bool operator== (const StatsAllocator<T1>&,
const StatsAllocator<T2>&) noexcept {
return true;
}
template <class T1, class T2>
bool operator!= (const StatsAllocator<T1>&,
const StatsAllocator<T2>&) noexcept {
return false;
}
#endif
// Local Variables:
// compile-command: "make -C $M2BUILDDIR/Macaulay2/e "
// indent-tabs-mode: nil
// End:
|