Brendon Lin
    • 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 New
    • 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 Note Insights Versions and GitHub Sync 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
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Implement Eytzinger Binary Search with Ripes By SC Lin (P76105059) ###### tags: `Computer Architecture` `Term Project` `RISC-V` ## Binary Search & Caching Binary search is one of the fastest search algorithms, being able to perform searches in O(log n) time (worst case). It is however limited by its nature of random-access. In an ideal world where memory access is as fast as arithmetic instructions this would not have been an issue, but our CPU architectures are built upon cache-based memories. Caching techniques read sequential blocks of data from the memory along with the actual requested data. Especially in binary searches, where the accessing pattern makes major jumps that gets halved with each iteration, we can see that this is not cache friendly. Therefore, an [Eytzinger Binary Search](https://algorithmica.org/en/eytzinger) is proposed as a modified version more suited for modern day architecture. ## Eytzinger Binary Search The concept is rather simple, suppose the root of the ordered-tree is indexed as 1. All subsequent children of a node at k is indexed as 2k and 2k+1. As shown below: ![](https://i.imgur.com/MeeaL8K.png) Eytzinger indexing. [source](https://algorithmica.org/en/eytzinger) We can see that the values used in each compare stage (same colour) are grouped in an contiguous arrangement, thereby improving cache performance. ### Eytzinger tranformation Thus, we have an additional function that performs an Eytzinger transform on an array. The code is adapted from this [C code](https://algorithmica.org/en/eytzinger) to assembly: ``` EYTZINGER: li a4 0 li a5 4 loop: #calculate where it belongs blt a2 a5 end # 1st child call addi sp sp -8 sw ra 0(sp) sw a5 4(sp) slli a5 a5 1 jal loop lw a5 4(sp) addi sp sp 4 # assign array elements add a6 a4 a0 # arr[k] lw a7 (0)a6 # slli a6 a5 2 add a6 a5 a3 # eyt[i] sw a7 (0)a6 addi a4 a4 4 # i++ # 2nd child call addi sp sp -4 sw a5 4(sp) slli a5 a5 1 addi a5 a5 4 jal loop lw ra 0(sp) lw a5 4(sp) addi sp sp 8 end: ret ``` The [author](https://algorithmica.org/en/eytzinger) also points out that "despite being recursive, this is actually a really fast implementation as all memory reads are sequential." Although one can observe that the write is still non-sequential. Testing the algorithm, our remapped array is: ![](https://i.imgur.com/UvurrtR.png) Which corresponds to the binary tree shown. We then implement the binary search part of the algorithm. Also based on the [C code of the same author](https://algorithmica.org/en/eytzinger). The original binary iterations are like-wise converted to the Eytzinger form, where the original left-right subintervals are replaced with our Eytzinger version of 2k or 2k+1. ``` BINARY: li a0 4 # k = 1 loop_bin: blt a2 a0 end_bin slli a5 a0 1 # 2*k add a6 a0 a3 # eyt[k] lw a7 0(a6) sub a6 a7 a1 # eyt[k] < x srli a6 a6 31 # get sign slli a6 a6 2 add a0 a5 a6 # k = 2 * k + (b[k] < x) j loop_bin end_bin: srli a0 a0 2 # remove memory offset ffs: andi a6 a4 0x1 beq a6 x0 end_ffs srli a4 a4 1 j ffs end_ffs: ret ``` The author optimised the code to be as CPU friendly as possible, by removing the branching present in the original binary-search. Which makes sense as the branching pattern is random based upon the search key, and thus won't benefit from branch predictions. Since the Eytzinger version of the branch only differs by a +1, the author proposed that we can replaced the `+1` with `+(eyt[k] < x)`, which, while consituting most of the code, avoids branching and improves pipelining. The outer while-loop does benefit from branch prediction as it will always be not-taken (in our assembly code) until the final iteration. ``` .data arr: .word 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 len: .word 15*4 eyt: .word 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 delim: .string "\n" .text main: la s0 arr lw a2 len la a3 eyt jal EYTZINGER li a1 1 li s1 16 loop_main: # search index of each number jal BINARY li a7 34 ecall la a0 delim li a7 4 ecall addi a1 a1 1 blt a1 s1 loop_main li a7, 10 ecall ``` Running the search with our binary search from values 1-15 with the code above, we have the correct indices returned by the code: ``` 0x0000 0x0001 0x0002 0x0003 0x0004 0x0005 0x0006 0x0007 0x0008 0x0009 0x000a 0x000b 0x000c 0x000d 0x000e Program exited with code: 0 ``` ### Cache Perfromance We then consider the caching performances. The first ~500 cycles corresponds to the Eytzinger tranformation: ![](https://i.imgur.com/EGVX1iW.png) The cache hit rate is already reaching +90% When we perform a single binary search: ![](https://i.imgur.com/cSskm7b.png) The hit rate goes over 98% Further binary searches have an average hit rate of 100%: ![](https://i.imgur.com/etfit2Q.png) But this is most likely due to the small size of the array. So let us increase the size of the array: |Size| 31 | 63 | 127 |255| 511 | |----|----|----|-----|---|-----| |Hit rate (1st time)| 98 | 96 | 95 | 92 | 92 | The hit rate seems to average out at around 92% with increasing size, which is still very good. Compared to the results of a [Diffuse the Bomb](https://hackmd.io/@arthur-chang/S1AM0D8Ht) implementation, which also follows a binary divide-and-conquer approach. Their implementation struggles to even achieve 90% at even small array sizes (<=30), this suggests that our Eytzinger approach is indeed more cache friendly. Below are different caching methods (in-order) for the 127-element array: direct mapping, fully-associative and 2-way associative. ![](https://i.imgur.com/mScBL7J.png) ![](https://i.imgur.com/lC0KCFs.png) ![](https://i.imgur.com/oVmj5fX.png) The associative mappings perfroms similarly while direct mapping suffers with larger arrays, but only for the Eytzinger sequence (noisy zigzags). Binary search-wise performance is roughly the same. Furthermore, the transformation takes up a bulk of the cycles with its O(n) time-complexity. This suggests that unless that data is already stored in Eytzinger form (or only needs to be processed once for many binary searches), it may not be practical to use the Eytzinger + Binary search for large data. ![](https://i.imgur.com/iWfpEiQ.png) (above) 16 searches only occur after the red line, before which is a Eytzinger transform of 127 elements. #### Cache Visualisation An example cache miss: ![](https://i.imgur.com/zKdVJio.png) An example cache hit: ![](https://i.imgur.com/BukzGkk.png) We see in the corresponding access address (in-order): tag (31~8), index (7~4), block(3~2) and offset (1~0)

    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