Austin Chen
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: ByteWise - Data Alignment tags: bytewise, c, case study --- # Data Alignment In this article, I will benchmark how **data alignment** could affect the performace of a program. Let us start with the experimental result. From the plot shown below, apparently, there is a performance impact on misaligned memory accesses. But **why?** ![](https://i.imgur.com/a329JHW.png) ## Memory addressing Computers commonly address the memory in word-sized chucks. A **word** is a computer's natural unit for data. Its size is defined by the computers architecture. Modern general purpose computers generally have a word-size of either 32-bit or 64-bit. To find out the natural word-size of a processor running a modern UNIX, one can issue the following commands: ```shell getconf WORD_BIT getconf LONG_BIT ``` In the case of a modern x86_64 computer, `WORD_BIT` would return `32` and `LONG_BIT` would return `64`. ### Alignment > #### C11 Stadndard § 3.1 alignment > requirement that objects of a particular type be located on storage boundaries with addresses that are particular multiples of a byte address Computer memory alignment has always been a very important aspect of computing. As we've already learned, old computers were unable to address improperly aligned data and more recent computers will experience a severe slowdown doing so. Only the most recent computers available can load misaligned data as well as aligned data[^1]. [^1]: Agner`s CPU blog, *"Test results for Intel's Sandy Bridge processor"*, https://www.agner.org/optimize/blog/read.php?i=142&v=t For instance, saving a 4 byte **int** in our memory will result in the intger being properly aligned without doing any extra work because an **int** on this architecture is exactly 4 byte which will fit perfectly into the first slot. ![](https://i.imgur.com/waVSRg1.png) If we instead decided to put a **char** and an **int** into our memory we would get a problem if we did so naively without worrying for alignement. This would need two memory accesses and some bitshifting to fetch the **int**. Effectively that means it will take at least two times as long as it would if the data were properly aligned. For this reason, computer scientists came up with the idea of adding padding to data in memory so it would be properly aligned. ![](https://i.imgur.com/Ghzr17u.png) ### Consequence of misalignment The consequence of data structure misalignment vary widely between architectures. Some **RISC, ARM** and **MIPS** processors will respond with an alignment fault if an attempt is made to access a misaligned address. Specialized processors such **DSPs** usually don't support accessing misaligned locations. Most modern general purpose processors are capable of accessing misaligned addresses, albeit at a steep performance hit of at least two times the aligned access time. Very modern X86_64 processors are capable of handling misaligned accesses without a performance hit. **SSE** requires data structures to be aligned per specification and would result in **undefined behavior** if attempted to be used with unaligned data. ## In Practice This chapter will introduce the alignment of **struct** in C. It will use a series of exmaples to do so. ### Example with struct ```c struct Test { char x; // 1 byte double y; // 8 bytes char z; // 1 bytes }; ``` Intuitively, this **Test** structure takes 1 byte + 8 bytes + 1 byte = 10 bytes, while the fact is 24 bytes. :::info :pencil2: A struct is always aligned to the largest type’s alignment requirements ::: ```c struct Test { char x; // 1 byte char z; // 1 bytes double y; // 8 bytes }; ``` Now it’s only 16 bytes which is the best we can do if we want to keep our memory **naturally aligned**. ```sh warning: padding struct to align ‘a’ [-Wpadded] 23 | int a; ``` ### Padding in the real world The previous chapters might lead you to believe that a lot of manual care has to be taken about data structures in C. In reality, however, it should be noted that just about every modern compiler will automatically use data structure padding depending on architecture. Some compilers even support the warning flag `-Wpadded` which generates helpful warnings about structure padding. These warnings help the programmer take manual care in case a more efficient data structure layout is desired. If desired, it's actually possible to prevent the compiler from padding a struct using either `__attribute((packed))` after a struct definition, `#pragma pack(1)` in front of a struct definition or `-fpack-struct` as a compiler parameter. ### Experiemnt Let us compare the **`diff`** of the following code. ```diff --struct Test1 { ++struct Test2 { char x; // 1 byte double y; // 8 bytes char z; // 1 bytes --} ++} __attribute__((packed)); ``` ```diff int main() { struct timespec start, end; -- struct Test1 test; ++ struct Test2 test; clock_gettime(CLOCK, &start); for (unsigned long i = 0; i < RUNS; ++i) { test.y = 1; test.y += 1; } clock_gettime(CLOCK, &end); struct timespec delta = diff(start, end); printf("%ld\n", delta.tv_nsec); } ``` 1. The benchmark was compiled with gcc using ```sh gcc -DRUNS=400000000 -DCLOCK=CLOCK_MONOTONIC -O0 -o test.out ``` 2. and run by the script ```sh printf "time,elapsed\n" > result.txt for i in {1..200}; do echo 3 > /proc/sys/vm/drop_caches; printf "%d, " $i; ./test.out; done >> result.txt ``` 3. and eventually use the following Python script to plot the final comparison result as we shown at the beginning of this article ```python import click import pandas as pd import matplotlib.pyplot as plt from pathlib import Path def hello(): cwd = Path.cwd() df1 = pd.read_csv(cwd/'result1.txt') df2 = pd.read_csv(cwd/'result2.txt') ax = df1.elapsed.plot.line() ax = df2.elapsed.plot.line(ax=ax) ax.legend(['unaligned', 'aligned']) plt.show() if __name__ == '__main__': hello() ``` [^ref]: Sven-Hendrik Haase, "Alignment in C", https://hps.vi4io.org/_media/teaching/wintersemester_2013_2014/epc-14-haase-svenhendrik-alignmentinc-paper.pdf [^ref]: https://www.kernel.org/doc/Documentation/unaligned-memory-access.txt

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully