Saturday, 3 December 2022

Chapter 25 // Exercise 15 - Principles & Practice Using C++

In this exercise I'm using Visual Studio 2019 and a modified version of the std_lib_facilities header found here.

Chapter 25 // Exercise 15

Measure the time (section 26.6.1) it takes to allocate 10,000 objects of random sizes in the [1000:0)-byte range using new; then measure the time it takes to deallocate them using delete.

Do this twice, once deallocating in the reverse order of allocation and once deallocating in random order. 

Then, do the equivalent  of allocating 10,000 objects of size 500 bytes from a pool and freeing them.

Then, do the equivalent of allocating 10,000 objects of random sizes in the [1000:0)-byte range on a stack and then free them (in reverse order). 

Compare the measurements . Do each measurement at least three times to make sure the results are consistent.

I split this up into several parts. For the object of random size I created a struct that holds a string, the string then reserves a random size between 0, 1000. A vector of that struct is created to hold the pointers to the object created.

---- Part 1 ----
(No pool or reserved allocation)
Allocate 10,000 objects: 1(19ms), 2(20ms), 3(21ms)
Deallocate in reverse order: 1(9ms), 2(10ms), 3(10ms)

---- Part 2 ----
(No pool or reserved allocation)
Allocate 10,000 objects: 1(20ms), 2(20ms), 3(21ms)
Deallocate in random order: 1(11ms), 2(11ms), 3(11ms)

For the ones with a pool I decided to not use new and delete and instead create a vector with a reserved size of 10,000 500-byte objects. That way when you pushback it won't need to allocate more space. Then "freeing" is as simple as just clearing the string.

---- Part 3 ----
(with reserved allocation of 500 bytes per object)
Allocate 10,000 objects: 1(14ms), 2(8ms), 3(8ms)
Deallocate in reverse order: 1(1ms), 2(1ms), 3(0ms)

---- Part 4 ----
(with reserved allocation of 500 bytes per object)
Allocate 10,000 objects: 1(14ms), 2(14ms), 3(14ms)
Deallocate in random order: 1(1ms), 2(1ms), 3(1ms)

---- Part 5 ----
(no pool, on std::stack)
Allocate 10,000 objects: 1(24ms), 2(24ms), 3(24ms)
Deallocate in random order: 1(15ms), 2(16ms), 3(16ms)

Allocating with a pool is always faster because the memory you need is right there. Memory pools are used a lot in games (you may hear them being called "banks" as well).

No comments:

Post a Comment