賴劭芊
    • 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
    # 2016q3 Homework1 (raytracing) contributed by <`shelly4132`> ### Reviewed by `HaoTse` - 可以再嘗試其他優化方法,例如 SIMD、pthread等等 - `git add` 時可以避免上傳執行結果的圖片 - 可以使用 **gnuplot** 一類的工具繪製出效能比較圖表 ## 開發環境 * 作業系統:Ubuntu 16.04 LTS * CPU:Intel(R) Core(TM) i5-4200U CPU @ 1.60GHz * Cache: * L1d cache: 32K * L1i cache: 32K * L2 cache: 256K * L3 cache: 3072K ## 事前準備 安裝一些必要的東西 ``` $ sudo apt-get update $ sudo apt-get install graphviz $ sudo apt-get install imagemagick ``` 先clone檔案下來執行看看 ``` $ git clone https://github.com/shelly4132/raytracing $ cd raytracing $ make $ ./raytracing ``` 結果 ``` # Rendering scene Done! Execution time of raytracing() : 3.258902 sec ``` 將O0改成Ofast,真的很快啊 ``` # Rendering scene Done! Execution time of raytracing() : 0.281827 sec ``` 可使用eog開啟圖片 ``` eog out.ppm ``` 或是將檔案轉換成png的格式 ``` convert out.ppm out.png ``` 圖片 ![](https://i.imgur.com/xcv1xPd.png) ## 光影追蹤程式 先執行 ```$ make clean```把剛剛產生的執行檔刪掉 接著執行 ```$ make PROFILE=1``` ``` cc -std=gnu99 -Wall -O0 -g -pg -c -o objects.o objects.c cc -std=gnu99 -Wall -O0 -g -pg -c -o raytracing.o raytracing.c cc -std=gnu99 -Wall -O0 -g -pg -c -o main.o main.c cc -o raytracing objects.o raytracing.o main.o -lm -pg ``` #### gprof -pg這個指令可以去追蹤程式執行的時間、幫助我們找到最耗時的function,以及每個function被呼叫的次數等等。 ```$ ./raytracing``` 再執行一次可以發現因為多了追蹤程式的時間所以總體執行時間變長了。 ``` # Rendering scene Done! Execution time of raytracing() : 7.058977 sec ``` 接下來就可以執行以下命令看結果 ``` $ gprof ./raytracing | less ``` 從以下可看出最耗時的為subtract_vector、dot_product和multiply_vector等function,因此優化應該從這前幾名開始著手。 ``` Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 20.88 0.58 0.58 56956357 0.00 0.00 subtract_vector 20.88 1.16 0.58 69646433 0.00 0.00 dot_product 10.08 1.44 0.28 31410180 0.00 0.00 multiply_vector 8.10 1.67 0.23 17836094 0.00 0.00 add_vector 7.20 1.87 0.20 4620625 0.00 0.00 ray_hit_object 6.66 2.05 0.19 13861875 0.00 0.00 rayRectangularIntersection 6.66 2.24 0.19 13861875 0.00 0.00 raySphereIntersection 6.12 2.41 0.17 17821809 0.00 0.00 cross_product 6.12 2.58 0.17 10598450 0.00 0.00 normalize 2.16 2.64 0.06 1 0.06 2.78 raytracing 1.44 2.68 0.04 1048576 0.00 0.00 ray_color 1.08 2.71 0.03 1048576 0.00 0.00 rayConstruction 0.90 2.73 0.03 3838091 0.00 0.00 length 0.36 2.74 0.01 4221152 0.00 0.00 multiply_vectors 0.36 2.75 0.01 2558386 0.00 0.00 idx_stack_empty ``` ### 開始優化 ### 方法一:force inline 在math-toolkit.h裡可以看到「static inline」這個關鍵字,拆開來看的話 #### static: 一個static函式表示它定義的範圍是local的,只會在這個檔案被看到。 #### inline: 在呼叫函式時會需要分配記憶空間因而需要額外的資源負擔,所以有些小函式我們可以「建議」編譯器將他設定為「行內函式」(Inline function),如果建議被採納,則該函式會自動在呼叫點展現為程式碼,行內函式建議可以直接定義於表頭檔案中。 所以我們可以把「static inline」理解為一個static的函式被加上了inline的屬性。 另外,如果編譯器優化設定為-O0,必須加上__attribute__((always_inline))強制展開,inline才會有作用。 於是我便在所有inline後面加上__attribute__((always_inline)) 然後執行! ``` # Rendering scene Done! Execution time of raytracing() : 4.085727 sec ``` 非常驚人的效果,執行時間一下子就掉了3秒左右! ### 方法二:Loop unrolling 這個方法顧名思義就是把迴圈展開,降低branch miss,雖然此法可能會造成程式的可讀性降低,和程式碼變得很冗長,但在一定限度內的展開迴圈的確是優化的好辦法。 以add_vector這個function來看,原本是i從0到2的迴圈,我直接把迴圈拿掉,把全部的運算寫出來。 #### 未展開 ```clike= static inline __attribute__((always_inline)) void add_vector(const double *a, const double *b, double *out) { for (int i = 0; i < 3; i++) out[i] = a[i] + b[i]; } ``` #### 展開後 ```clike= static inline __attribute__((always_inline)) void add_vector(const double *a, const double *b, double *out) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; } ``` 執行後可以發現時間又降低了大概1秒左右 ``` # Rendering scene Done! Execution time of raytracing() : 3.141350 sec ``` 現在我們再用gprof看一遍,可以發現subtract_vector、dot_product和multiply_vector那些function的排名都掉到很後面了,而rayRectangularIntersection、raySphereIntersection等等則變成比例較高的。 ``` Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 37.19 0.71 0.71 13861875 0.00 0.00 rayRectangularIntersection 21.47 1.12 0.41 13861875 0.00 0.00 raySphereIntersection 9.43 1.30 0.18 2110576 0.00 0.00 localColor 9.43 1.48 0.18 10598450 0.00 0.00 normalize 6.28 1.60 0.12 4620625 0.00 0.00 ray_hit_object 4.19 1.68 0.08 2110576 0.00 0.00 compute_specular_diffuse 4.19 1.76 0.08 1048576 0.00 0.00 ray_color 3.14 1.82 0.06 1048576 0.00 0.00 rayConstruction 2.09 1.86 0.04 1241598 0.00 0.00 reflection 1.05 1.88 0.02 1 0.02 1.91 raytracing 0.52 1.89 0.01 2520791 0.00 0.00 idx_stack_top 0.52 1.90 0.01 1241598 0.00 0.00 protect_color_overflow 0.52 1.91 0.01 1241598 0.00 0.00 refraction 0.00 1.91 0.00 2558386 0.00 0.00 idx_stack_empty 0.00 1.91 0.00 1204003 0.00 0.00 idx_stack_push 0.00 1.91 0.00 1048576 0.00 0.00 idx_stack_init 0.00 1.91 0.00 113297 0.00 0.00 fresnel 0.00 1.91 0.00 37595 0.00 0.00 idx_stack_pop ``` ### 方法三:OpenMP 從上面的結果我們看到rayRectangularIntersection、raySphereIntersection所佔耗時間最多的2個,而他們剛好都是被raytracing.c裡的raytracing()所間接呼叫的,又正好raytracing()裡每個pixel是可以獨自運算的,所以我們可以對他做平行處理增加效能。 #### OpenMP簡介 OpenMP(Open Multi-Processing)是一套支援跨平台共享記憶體方式的多執行緒並行的編程API,使用C,C++和Fortran語言,可以在大多數的處理器體系和作業系統中執行,包括Solaris, AIX, HP-UX, GNU/Linux, Mac OS X, 和Microsoft Windows。包括一套編譯器指令、庫和一些能夠影響執行行為的環境變數。 * 編譯時要記得在Makefile中的CFLAGS加上-fopenmp,LDFLAGS加上-lgomp 一開始自己在raytracing()的for迴圈上加了下面這一行 ``` #pragma omp parallel for private(stk), private(object_color), private(d) ``` 但執行出來的時間幾乎沒有減少 ``` # Rendering scene Done! Execution time of raytracing() : 3.070660 sec ``` 後來才發現原來我忘記去設定thread的數量 ``` #pragma omp parallel for num_threads(50) private(stk), private(object_color), private(d) ``` 開了50個thread後時間就比之前又降了1秒左右 ``` # Rendering scene Done! Execution time of raytracing() : 1.959896 sec ``` 把gprof拿掉之後,距離Ofast最佳化的時間還有一段差距 ``` # Rendering scene Done! Execution time of raytracing() : 0.979613 sec ``` #### 語法說明 * for:用在 for 迴圈之前,會將迴圈平行化處理。(註:迴圈的 index 只能是 int) * private:讓每個執行緒中,都有一份變數的複本,以免互相干擾。 * num_threads:設定平行化時執行緒的數量。 ## 參考資料 * [C語言inline詳細講解](http://www.cnblogs.com/cnmaizi/archive/2011/01/19/1939686.html) * [彥寬學長](https://embedded2016.hackpad.com/2016q1-Homework-2A-wOu40KzMaIP) * [陳品睿學長](https://embedded2016.hackpad.com/2016q1-Homework-2A-bLGQtRraTES) * [vvn](https://hackmd.io/MYQwpgnARsBMUFoBmAWAjADgSsBmLGSuArAgAwDsFKAJmmAGxJgbFA==?view#2016q3-homework1-raytracing) * [勃興](https://hackmd.io/s/BygM4qP6#2016q3-homework1-raytracing) * [簡易的程式平行化-OpenMP(五) 變數的平行化](https://kheresy.wordpress.com/2006/09/22/%E7%B0%A1%E6%98%93%E7%9A%84%E7%A8%8B%E5%BC%8F%E5%B9%B3%E8%A1%8C%E5%8C%96%EF%BC%8Dopenmp%EF%BC%88%E4%BA%94%EF%BC%89-%E8%AE%8A%E6%95%B8%E7%9A%84%E5%B9%B3%E8%A1%8C%E5%8C%96/)

    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