何俊逸
    • 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
      • Invitee
    • Publish Note

      Publish Note

      Everyone on the web can find and read all notes of this public team.
      Once published, notes can be searched and viewed by anyone online.
      See published notes
      Please check the box to agree to the Community Guidelines.
    • 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
    • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync 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
Invitee
Publish Note

Publish Note

Everyone on the web can find and read all notes of this public team.
Once published, notes can be searched and viewed by anyone online.
See published notes
Please check the box to agree to the Community Guidelines.
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 Homework01 (compute-pi) contrubuted by <`hugikun999`> Reviewed by <`heathcliffYang`> ## Reviewed by `heathcliffYang` 除了比較優化之餘,也可以嘗試其他更多pi的演算法去比較。 ## inplement * cycle finding 對於一個f(x),給定一初始值,請找到第一次開使重覆的地方。(即Xi = Xj)一旦出現這種情況就會週期性出現。 ```C memset(void *str,int c,size_t z) ``` 說明:將這個指標所指向的前z個字節設為"c"; 回傳值:pointer。 * Memoization 一種最佳化的技巧,紀錄function call的結果,當有同樣的輸入發生時直接回傳cache的東西。 * [相關pi的演算法](https://en.wikipedia.org/wiki/Category:Pi_algorithms) * 時間函數 (1)UTC:世界標準時間。 (2)calender time:日曆時間,即相對時間,對不同的編譯系統會有不同標準時間點。 (3)clock tick:計時單元,其時間長短由CPU決定。 * 時間精準度: (1)clock_gettime():取得目前時間。(1ns) (2)Windows:QueryPerformanceCounter():取得rdtsc的counter數。( < 1ns) (3)clock():精確度只到ms。 * xtime: (1)microsecond:微秒 (2)ms:毫秒 (3) 從1970/1/1開始計時,所謂的實時時鐘,精確度是us。 * jiffies: (1)每一個tick是以系統頻率決定,若是200MHz則可以精確到5ns。 ## AVX * 延伸SSE指令集 [這裡](https://isite.tw/2016/01/24/14639)有歷代指令集的介紹。最大的特點是將XMM 128bit -> YMM 256bit,提高CPU在處理特定向量和浮點數運算的效率。 * 4個operands 通過VEX prefix實現4個operands,表示為dest、src1、src2、src3。雖然有4個operand,但速度不會到4x。VEX又可分為128和256版,分別集成escape prefix、SIMD prefix、REX prefix。 * 指令編碼格式 ![](https://i.imgur.com/miFdddb.jpg) VEX的部份 (1)提供寄存器寻址。 (2)提供 escape prefix 与 SIMD prefix (3)指示 operand 是 128 位还是 256 位 (4)提供 REX.RXB 的作用 * 實現不改變destination * AVX512 再將256bit擴大到512bit。 * AVX相關語法 [這裡](https://software.intel.com/en-us/articles/introduction-to-intel-advanced-vector-extensions)是基本介紹每個字的意思。 [這裡](https://software.intel.com/sites/landingpage/IntrinsicsGuide/#expand=4635,198,100,112)是AVX還有其它SSE的版本一些相關用法,裡面有每個function的做法和對應的assembly code。 ## compute_pi 在開使之前先用```time```測試了raytracing,結果發現由main.c的clock_gettime()會小於由```time```所測出來的real。 ``` # Rendering scene Done! Execution time of raytracing() : 1.059423 sec real 0m1.064s user 0m8.364s sys 0m0.028s ``` ### Makefile (一) 我在寫Makefile的時候發現我的tab後面加的東西沒有變成指令,查了一下覺得可能是因為我好像把tab變成四個空白。 [參考資料](http://koen.iteye.com/blog/602240) (二) 在```Makefile```中的```gencsv```裡有寫到100、500、25000,經過測試知道100是N的初始值,500是每次增加的大小,25000是N的上限。 ``` gencsv: default for i in `seq 100 500 25000`; do \ printf "%d," $$i;\ ./benchmark_clock_gettime $$i; \ done > result_clock_gettime.csv ``` ### gnuplot 這次使用的是.csv檔和上一次不一樣,按照上次的去做runtime.gp會一直出現```"runtime.gp", line 11: warning: Skipping data file with no valid points```這個錯勿,參考[Vivian Lin](https://hackmd.io/MYZgpgTAJmCsUFpYDNiwQFnMhBOAhmAGx5gYCMY+IUuRy5QA?view#)在其中多加一行```set datafile separator ","```就可以成功吃到資料了。 ``` set xlabel 'N' set ylabel 'Time(sec)' set autoscale fix set style fill solid set datafile separator "," set title 'runtime' set term png enhanced font 'Verdana,10' set output 'time.png' plot 'result_clock_gettime.csv' using 1:2 title 'baseline' with linespoints, \ 'result_clock_gettime.csv' using 1:3 title 'openmp_2' with linespoints, \ 'result_clock_gettime.csv' using 1:4 title 'openmp_4' with linespoints, \ 'result_clock_gettime.csv' using 1:5 title 'AVX' with linespoints, \ 'result_clock_gettime.csv' using 1:6 title 'AVX+unroll' with linespoints, \ ``` ### file * openMP 在編譯時記得要在gcc後加上參數```-fopenmp```,檔案內也要記得```#include <omp.h>```,不然就算加上一些openmp的語法也不會有作用。[這裡](https://kheresy.wordpress.com/2006/09/13/%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%8C%EF%BC%89%E8%AA%9E%E6%B3%95%E8%AA%AA%E6%98%8E/)有語法的介紹和一些範例。 ```C #pragma omp parallel num_threads(threads) ``` 這個意思是指定threads,在()內填入想指定的數目,通常thread越高就會跑越快,但是會有一個極限。 ```C #pragma omp for private(x) reduction(+:pi) ``` for是將底下的for迴圈拆開來分給每個thread去執行。 private(x)是讓每個thread都有一份自己的x而不去影響到其它thread所存的東西,如果改到別的thread存的東西會造成錯誤。 reduction(+:pi)很類似private(),讓大家都有一份複本各自運算,不同的是最後再將所有的```pi```相加起來。 * AVX ```C register __m256d ymm0, ymm1, ymm2, ymm3, ymm4; ``` 宣告出4個256bit的register。```__m256d```是指4個64bit的double。 ```C ymm0 = _mm256_set1_pd(1.0); ``` 將4個double分別紀錄1.0進去。 ```C ymm2 = _mm256_set_pd(dt * 3, dt * 2, dt * 1, 0.0); ``` 將4個double分別照順序記錄dt*3、dt*2 、dt*1、dt。 ```C ymm4 = _mm256_setzero_pd(); ``` 全部bit記錄為0。 ```C ymm3 = _mm256_add_pd(ymm3, ymm2); ``` 將ymm3加上ymm2存到ymm3中。add可以替換sub、mul、div之類的算術方法,也可換為store之類的功能。 ```C double tmp[4] __attribute__((aligned(32))); ``` (1)__attribute__可以設置函數屬性(Function Attribute)、變量屬性(Variable Attribute)和類型屬性(Type Attribute)。 (2) aligned(32) 該聲明將強制編譯器確保(盡它所能)分配空間時採用32字節對齊方式。取32byte因為一個double是8byte,須要4個即為32byte。 ### 未優化 (一) (1)```make check``` ``` time ./time_test_baseline N = 400000000 , pi = 3.141593 3.49user 0.00system 0:03.49elapsed 100%CPU (0avgtext+0avgdata 1780maxresident)k 0inputs+0outputs (0major+85minor)pagefaults 0swaps time ./time_test_openmp_2 N = 400000000 , pi = 3.141593 3.58user 0.00system 0:01.79elapsed 199%CPU (0avgtext+0avgdata 1788maxresident)k 0inputs+0outputs (0major+86minor)pagefaults 0swaps time ./time_test_openmp_4 N = 400000000 , pi = 3.141593 3.80user 0.00system 0:00.95elapsed 398%CPU (0avgtext+0avgdata 1784maxresident)k 0inputs+0outputs (0major+92minor)pagefaults 0swaps time ./time_test_avx N = 400000000 , pi = 3.141593 1.01user 0.00system 0:01.01elapsed 100%CPU (0avgtext+0avgdata 1756maxresident)k 0inputs+0outputs (0major+83minor)pagefaults 0swaps time ./time_test_avxunroll N = 400000000 , pi = 3.141593 0.98user 0.00system 0:00.98elapsed 100%CPU (0avgtext+0avgdata 1792maxresident)k 0inputs+0outputs (0major+84minor)pagefaults 0swaps ``` (2)由100~50000的圖 ![](https://i.imgur.com/fxkYxCV.png) (二) 我更改了```Makefile```裡面的N,發現了N從0~20的區間都會跑很久,甚至是懷疑N=1就卡住了,從perf top 監看,發現一直```compute_pi_avx```處於熱點,目前還不確定是什麼原因,等看完AVX相關的文件應該就會比較了解。 ## 優化 * 信賴區間 (一) 從圖中可以看到有些超出範圍太多,可以視為例外並沒有太多參考價值,故對這些數據取2個標準差可以使其有更精準的量測結果。 我在```benchmark_clock_gettime.c```中多寫了一個用來計算標準差的function,當中有多用到```math.h```這個library,所以在```Makefile```中必須多加上```-lm```才能執行。 (1)Makefile ```C default: computepi.o $(CC) $(CFLAGS) computepi.o time_test.c -DBASELINE -o time_test_baseline $(CC) $(CFLAGS) computepi.o time_test.c -DOPENMP_2 -o time_test_openmp_2 $(CC) $(CFLAGS) computepi.o time_test.c -DOPENMP_4 -o time_test_openmp_4 $(CC) $(CFLAGS) computepi.o time_test.c -DAVX -o time_test_avx $(CC) $(CFLAGS) computepi.o time_test.c -DAVXUNROLL -o time_test_avxunroll $(CC) $(CFLAGS) computepi.o benchmark_clock_gettime.c -o benchmark_clock_gettime -lm ``` 注意```-lm```必須加在gcc的最後面,如果直接加在```CFLAGS```後面會錯。 (2)圖(sample = 10) ![](https://i.imgur.com/JD15c4X.png) 雖然次數的間隔比之前大,但是從圖中可以看到趨勢線已經比較少有極端值的存在了。 (3)圖(sample = 25) ![](https://i.imgur.com/Dvs4dKB.png) 這次取25個sample震盪幅度又變更小了,可是我的openmp4很奇怪,會有一些超乎常理的暴增。目前覺得是因為我的電腦只有2個threads,所以宣告成四個threads時會有互搶的問題,所以才有些會超高。另一個是有些openmp4比AVX還要低,AVX一次處理4個register,openmp4也像是一次跑4個的概念,但是卻比AVX還要快。 (4)圖 (sample = 25) ![](https://i.imgur.com/UjuUr3z.png) 驗證在(三)中的想法,我將AVX中加上了openmp去嘗試,結果發現圖非常的醜,應該是不能用private去讓每個thread有自己的256bit register,可是也有一些低的AVX+openmp可以低到跟openmp4一樣了,可見最低值還是有下降。 另外我增跑了openmp8,雖然沒有比openmp4更低卻有比openmp4更穩定。 * Error check (一) 除了花費時間外,從下面的圖中可以看出來由五種方法所算出來的正確性,剛開始N很小時所做出來的正確性很低,當N變大時正確性也提高。 ![](https://i.imgur.com/6JQlUdY.png) > 參考自heathcliffYang (二) AVX和AVX+unroll會有震盪是因為每次加4和每次加16,如果N不是4或著16的倍數就會造成少算的結果,所以會產生震盪。將N和每次的差都改為16的倍數就不會和其它演算法有差。 ![](https://i.imgur.com/XSMIhmL.png)

Import from clipboard

Paste your webpage below. It will be converted to Markdown.

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 is not available.
Upgrade
All
  • All
  • Team
No template found.

Create custom 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

How to use Slide mode

API Docs

Edit in VSCode

Install browser extension

Get in Touch

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

No updates to save
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