Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * comparsion of standard allocator and simple segregated storage allocator
- * requires c++0x in line 25 (for type size assertions)
- */
- // removes type size check for your own risk
- #define CHECK_SIZE
- #include <iostream>
- #include <sys/timeb.h>
- #include <cstdlib>
- typedef long double ldouble;
- typedef unsigned int uint;
- ldouble ftime()
- {
- timeb curr;
- ftime(&curr);
- return curr.time+curr.millitm/1000.0;
- }
- template <class T, size_t size>
- class pool {
- public:
- pool()
- {
- #ifdef CHECK_SIZE
- static_assert(sizeof(T)>=sizeof(T*), "Chunk size is less than machine word size!");
- #endif
- storage_ = reinterpret_cast<T*>(malloc(size*sizeof(T)));
- T* ptr;
- for (ptr = storage_; ptr != storage_ + (size-1); ++ptr) {
- *reinterpret_cast<T**>(ptr) = ptr+1;
- }
- *reinterpret_cast<T**>(ptr) = 0;
- free_chunk_ = storage_;
- }
- ~pool()
- {
- free(storage_);
- }
- T* get()
- {
- if (!free_chunk_) {
- throw std::bad_alloc();
- }
- T* result = free_chunk_;
- free_chunk_ = *reinterpret_cast<T**>(free_chunk_);
- return result;
- }
- void free(T* block)
- {
- *reinterpret_cast<T**>(block) = free_chunk_;
- free_chunk_ = block;
- }
- private:
- T* free_chunk_;
- T* storage_;
- };
- template <typename T>
- void test(int N)
- {
- T** ptrs = new T*[N];
- // test standard allocator
- ldouble start = ftime();
- for (uint i = 0; i<N; ++i) {
- ptrs[i] = new T;
- }
- for (uint i = 0; i<N; ++i) {
- delete ptrs[i];
- }
- std::cout << "Standard allocator with " << N << " objects: " << ftime()-start << " seconds" << std::endl;
- pool<T, 50000000> pool_;
- start = ftime();
- for (uint i = 0; i<N; ++i) {
- ptrs[i] = new(pool_.get()) T;
- }
- for (uint i = 0; i<N; ++i) {
- ptrs[i]->~T();
- pool_.free(ptrs[i]);
- }
- std::cout << "Simple segregated storage allocator with " << N << " objects: " << ftime()-start << " seconds" << std::endl;
- delete ptrs;
- }
- int main(int argc, char **argv)
- {
- uint N;
- if (argc > 1) {
- N = atoi(argv[1]);
- }
- else {
- N = 10000000;
- }
- test<long int>(N);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement