Low-Level Programming: Post 20 17/03/2016
March 17th 2016 is the date of the twentieth and last lesson on Low-Level Programming (in which I will need to post on this blog needed for the module).
Note: This post is the updated version of the last lesson on Low-Level Programming, as I now have the slides from the lesson to show to you.
Below are the main points taken from the lesson...
Note: This post is the updated version of the last lesson on Low-Level Programming, as I now have the slides from the lesson to show to you.
Below are the main points taken from the lesson...
- Bitmasks: What are they and how to use them.
- Memory Padding/Alignment: What they are and how they compare to exceptions.
- Custom Allocations: How to maximize storage of flags or conditions.
- Summary: End of!
Bitmasks
Bitmasks
- Last Week: Last week, we experimented with Bitfields which allow us to store booleans as a single bit inside a data type i.e. an int has 32 bit, so we can have 32 conditions.
- Another Approach: We can actually approach the same problem from a different perspective. Bitmasking allows the use of logical operators to determine the bit’s status.
- Padding: If we’re not concerned with controlling the padding or alignment of our data, it’s possible to store the data in a standard variable, either locally or globally.
Example Usage
- Space Conscious: As with bitfields, reducing the number of booleans used to store conditionals in our code saves memory (due to minimum addressable types) over several booleans.
- Arbitrary Args: Imagine a situation where we need to pass many args through to a function and we don’t want to wrap it in a struct, we could chose a field of bits instead. Each bit or bits representing a value or state.
- Component Flags: Game objects are often formed of different component types. Using a mask, an object can store all of it’s component types effectively i.e. an object could be a renderable and movable component.
Vector of Bool
- STL: The STL actually has a special container type for storing arrays of bits. It's the STL::Vector<bool> container class.
- Non-Standard: It works differently to standard containers in the STL and actually breaks some of the generic ways of interacting with containers.
- Disliked: For this reason, it's a useful but disliked container class.
Custom Allocators
New/Delete
- Replacements: New & Delete are the functions that are responsible for allocating dynamic memory when you instantiated an object on the heap. We can replace these functions, but why?
- Usage Errors: Using more than one delete on new memory yields undefined behaviour. If the new operator keeps a list of allocated addresses & the delete operator removes them for the list, it's easy to detect this use case & prevent undefined behaviour.
- Underruns/Overruns: Programming mistakes can lead to data overruns (writing beyond the allocated memory) or underruns (writing prior to the allocation). The allocate can place markers at the beginning and end of the memory block and log these.
New/Delete Continued
- Efficiency: The versions of new & delete that ship with compiles are general-purpose allocators & deallocators. The allocators therefore apply a middle of the road approach not favouring any one particular usage pattern of memory.
- Usage Patterns: If you have an impressively good understanding of your program’s memory usage patterns, a custom new and delete operator may outperform the default shipped versions.
- Performance Increase: You can, if correctly implemented gain some significant performance benefits by adapting the allocation memory model to match your programs memory signature.
- Usage Statistics: How do we determine our programs memory usage patterns? We can accomplish this through logs.
- Allocators: We can customise the allocators & deallocators can be used to collect information regarding memory usage.
- Max Memory: Using this technique it’s possible to establish the baseline for memory usage but also the maximum dynamic memory usage requirement for your game.
Custom Allocators Continued
- Alignment: The previous example demonstrates how easy it is to create a custom allocator. However, there's a couple issues with it and one in particular worth mentioning. Alignment.
- Memory Placement: Many computer architectures require that data of particular types are placed in memory at particular kinds of addresses i.e. pointers should occur at addresses that are multiples of 4 (four-byte aligned) or that doubles multiples of 8.
- Issues: This could lead to exceptions at runtime. Some architectures are more forgiving, but will offer better performance if alignment is maintained. Malloc is byte aligned, but adding the signature could throw off alignment.
C++ Custom Memory
- Summary:
- To detect usage errors.
- Collect statistics about dynamically allocated memory.
- Increase speed of allocation & deallocations.
- To reduce the space overhead of default memory management.
- Compensate for sub-optimal alignment in default allocator.
Memory Alignment
- Access: A computer accesses memory by a single memory word at a time. As long as the memory word size is at least as large as the smallest primitive data type, aligned accesses will always be accessed within a single word.
- Split: If the highest and lowest bytes in a block of data are not within the same word, the computer must split the data access into multiple memory accesses.
- TLB/Page Faults: To handle data split across multiple words, the processor must verify both pages before execution or be able to handle a TLB (translation lookaside buffer) miss or page fault during memory access as the instructions are executed.
Atomics
- Remember those: When a single word is accessed, the operation is atomic. Other devices need to wait until the read or write has been fully completed.
- Across the words: This is not necessarily the case when accessing multiple words e.g. the first word can be read by one device, both words written by another device and then the second word read by the first device. This is bad, as the data has now been altered mid-way through a read. Think of concurrency issues in threading.
- X86: X86 is a platform that can handle both aligned and misaligned memory access. However, alignment is preferred for performance reasons.
- Atomic Instructors: Modern CPUs provide atomic instructions (covered in previous lessons). This prevents issues with concurrent access to the same address.
- Turn a Bit On: For atomic operations to operate correctly, the address you pass them must be at least four-byte aligned. This is due to atomic instructions and virtual memory.
- Misaligned: If the address is misaligned, the operation requires at least two memory access operations. If data spanned two pages of virtual memory, this could lead to one part loaded and a page fault being generated when loading the second. The fault would destroy the atomicity of the operation. Because of this addresses must be at least four-byte aligned.
Padding
- Alignment Concerns: You can see from the previous slides how ensuring data is correctly aligned in memory is essential to performance & stability.
- Compilers: Compilers will ensure this behaviour for you. Forcing data types to be padded out to ensure they can be read in alignment. This can potentially lead to memory wastage.
- Padding: It’s possible to create custom data structures and re-assign the basic types memory bits (last week). We can then pad out our structure to ensure optimum performance and memory usage.
Memory Padding
Padding Continued
- Backwards Compatibility: As some architectures and older CPUs would crash when accessing data on odd memory addresses, the compiler will ensure all fields start on an even memory address.
- Performance: As demonstrated earlier, accessing data in larger granularities and correctly aligned fields mean a huge boost to the CPU’s performance when accessing memory.
- Placement: Padding can be added in between members to ensure the individual data items are on aligned boundaries. Data structures will often have members with different alignment requirements.
- End-Of: The other area in which padding can be added is at the end of the structure. The compiler will add a final unnamed member. This allows each member of an array of structures to aligned.
- Reordering: Consider reordering to make maximum use of the space. For example: two chars next to each other, followed by a short.
- No Except: Packed structures (forcing the alignment) is normally used to conserve memory, they can also be used to force the size of data before transmitting it over a network. There’s no need to waste extra space with padding.
- Performance Trade-off: Of course, whenever we use packed structures in this manner, there’s a space/time compromise being made. Slower performance for less memory.
- Typical Alignments [32 Bits]:
- A char (one byte) will be 1-byte aligned.
- A short (two bytes) will be 2-byte aligned.
- An int (four bytes) will be 4-byte aligned.
- A long (four bytes) will be 4-byte aligned.
- A float (four bytes) will be 4-byte aligned.
- A double (eight bytes) will be 8-byte aligned on Windows and 4-byte aligned on Linux
- Any pointer (four bytes) will be 4-byte aligned. (e.g.: char*, int*)
For the practical in the lesson, we were given two simple options, work on the Chat Program, or leave the lesson early. I decided to try and work on the Chat Program and generally look at how SFML works. Sadly, I couldn't really work on the Chat Program since it had some errors. I will be attempting to work on them over the holiday. Despite this, however, I managed to complete the battleship game and made a good start on the Supporting Document needed for the assignment, with the objective being trying to fit the game into the Chat Program.


