MorphoGraphX  2.0-1-227
CachedAlloc.hpp
Go to the documentation of this file.
1 //
2 // This file is part of MorphoGraphX - http://www.MorphoGraphX.org
3 // Copyright (C) 2012-2016 Richard S. Smith and collaborators.
4 //
5 // If you use MorphoGraphX in your work, please cite:
6 // http://dx.doi.org/10.7554/eLife.05864
7 //
8 // MorphoGraphX is free software, and is licensed under under the terms of the
9 // GNU General (GPL) Public License version 2.0, http://www.gnu.org/licenses.
10 //
11 #ifndef CACHED_ALLOC_HPP
12 #define CACHED_ALLOC_HPP
13 
14 #include <Config.hpp>
15 
16 #ifdef THRUST_BACKEND_CUDA
17 
18 #include <cuda_runtime.h> // this header is not automatically included in Thrust headers in CUDA-9.0RC
19 #include <thrust/system/cuda/vector.h>
20 #include <thrust/system/cuda/execution_policy.h>
21 #include <thrust/host_vector.h>
22 #include <thrust/generate.h>
23 #include <thrust/pair.h>
24 #include <iostream>
25 #include <map>
26 #include <list>
27 
28 // Modified for use with MorphoGraphX
29 //
30 // Example by Nathan Bell and Jared Hoberock
31 // (modified by Mihail Ivakhnenko)
32 //
33 // This example demonstrates how to intercept calls to get_temporary_buffer
34 // and return_temporary_buffer to control how Thrust allocates temporary storage
35 // during algorithms such as thrust::reduce. The idea will be to create a simple
36 // cache of allocations to search when temporary storage is requested. If a hit
37 // is found in the cache, we quickly return the cached allocation instead of
38 // resorting to the more expensive thrust::cuda::malloc.
39 //
40 // Note: this implementation cached_allocator is not thread-safe. If multiple
41 // (host) threads use the same cached_allocator then they should gain exclusive
42 // access to the allocator before accessing its methods.
43 
44 namespace mgx
45 {
46  // cached_allocator: a simple allocator for caching allocation requests
47  class CachedAllocator
48  {
49  public:
50  // just allocate bytes
51  typedef char value_type;
52 
53  CachedAllocator() : maxBuffers(10) {}
54  ~CachedAllocator() { clear(); }
55 
56  char* allocate(size_t n);
57  void deallocate(char* ptr, size_t n);
58  void clear();
59 
60  private:
61  typedef std::pair<size_t, char*> FreeBlockPair;
62  typedef std::list<FreeBlockPair> FreeBlockList;
63  typedef std::map<char*, size_t> AllocatedBlockMap;
64 
65  uint maxBuffers;
66  FreeBlockList freeBlocks;
67  AllocatedBlockMap allocatedBlocks;
68  };
69 
70  extern CachedAllocator cachedAlloc;
71 }
72 #endif
73 #endif
n
#define n
Definition: Eigenvalues.hpp:36
uint
unsigned int uint
Definition: MorphoGraphX.hpp:14
mgx
Distributed matrix library.
Definition: Assert.hpp:26