洪嘉志
    • 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
    # Homework 3 : SoftCPU ###### tags: `Computer Architecture 2022` ## Prerequisites First, we need to finish [Lab2: RISC-V RV32I[MACF] emulator with ELF support](https://hackmd.io/@sysprog/SJAR5XMmi). 1. Prepare GNU Toolchain for RISC-V. See The xPack GNU RISC-V Embedded GCC ``` $ cd /tmp $ wget https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v12.2.0-1/xpack-riscv-none-elf-gcc-12.2.0-1-linux-x64.tar.gz $ tar zxvf xpack-riscv-none-elf-gcc-12.2.0-1-linux-x64.tar.gz $ cp -af xpack-riscv-none-elf-gcc-12.2.0-1 $HOME/riscv-none-elf-gcc ``` 2. Configure $PATH ``` $ cd $HOME/riscv-none-elf-gcc $ echo "export PATH=`pwd`/bin:$PATH" > setenv ``` 3. Once step (1) and (2) are complete, you can simply update $PATH environment variable via: ``` $ cd $HOME $ source riscv-none-elf-gcc/setenv ``` 4. Then, do the steps of [Lab3: srv32 - RISCV RV32IM Soft CPU](https://hackmd.io/@sysprog/S1Udn1Xtt) ``` export CROSS_COMPILE=riscv-none-elf- sudo apt install autoconf automake autotools-dev curl gawk git \ build-essential bison flex texinfo gperf libtool patchutils bc git \ libmpc-dev libmpfr-dev libgmp-dev gawk zlib1g-dev libexpat1-dev git clone --recursive https://github.com/riscv/riscv-gnu-toolchain cd riscv-gnu-toolchain mkdir -p build && cd build ../configure --prefix=/opt/riscv --with-isa-spec=20191213 \ --with-multilib-generator="rv32i-ilp32--;rv32im-ilp32--;rv32imac-ilp32--;rv32im_zicsr-ilp32--;rv32imac_zicsr-ilp32--;rv64imac-lp64--;rv64imac_zicsr-lp64--" make -j$(nproc) ``` When I do `make -j$(nproc)` , I find a problem. It said it can't create directory. ``` mkdir: 無法建立 「/opt/riscv」 目錄: 拒絕不符權限的操作 mkdir: 無法建立 「/opt/riscv」 目錄: 拒絕不符權限的操作 make[2]: *** [Makefile:2818:installdirs] 錯誤 1 make[2]: 離開目錄「/home/hung/riscv-gnu-toolchain/build/build-gdb-newlib」 make[1]: *** [Makefile:2558:install] 錯誤 2 make[1]: 離開目錄「/home/hung/riscv-gnu-toolchain/build/build-gdb-newlib」 make: *** [Makefile:537:stamps/build-gdb-newlib] 錯誤 2 ``` I manually created the directory and set permissions. ``` cd $HOME cd /opt sudo mkdir riscv sudo chmod 777 /opt/riscv ``` And check if the directory have read and write permissions. After doing this, it can run smoothly. ``` hung@hung-MS-7B79:/opt$ ls -l 總用量 4 drwxrwxrwx 2 root root 4096 11月 21 23:49 riscv ``` 5. Install the dependent packages. ``` sudo apt install build-essential lcov ccache libsystemc-dev ``` 6. Install `verilator` and set environment variable ```diff cd $HOME git clone https://github.com/verilator/verilator cd verilator git checkout stable export VERILATOR_ROOT=`pwd` + autoconf // Create ./configure script, or it can find the directory of configure ./configure make export VERILATOR_ROOT=$HOME/verilator export PATH=$VERILATOR_ROOT/bin:$PATH ``` 7. Get the source ``` git clone https://github.com/sysprog21/srv32 ``` ## Run RTL sim and ISS sim Then we can use the following command to run RTL sim and ISS sim. ``` cd srv32 make hw3 ``` The following result is from my [Homework 2 - RISC-V Toolchain](https://hackmd.io/KqhB3hrVRHGjFbx91qQIcg) ### HW2 Simulation results RTL Simulation result ``` Input:[1,2,3,4,5,] Output:[5,4,3,2,1,] Input:[1,2,] Output:[2,1,] Input:[1,2,3,4,5,6,7,8,9,10,] Output:[10,9,8,7,6,5,4,3,2,1,] Excuting 34642 instructions, 45808 cycles, 1.322 CPI Program terminate - ../rtl/../testbench/testbench.v:434: Verilog $finish Simulation statistics ===================== Simulation time : 0.213 s Simulation cycles: 45819 Simulation speed : 0.215113 MHz ``` ISS (Instruction Set Simulator) result ``` Input:[1,2,3,4,5,] Output:[5,4,3,2,1,] Input:[1,2,] Output:[2,1,] Input:[1,2,3,4,5,6,7,8,9,10,] Output:[10,9,8,7,6,5,4,3,2,1,] Excuting 34642 instructions, 45808 cycles, 1.322 CPI Program terminate Simulation statistics ===================== Simulation time : 0.017 s Simulation cycles: 45808 Simulation speed : 2.688 MHz ``` ### HW3 C code And I choose another problem from [leetcode 15 - 3Sum](https://leetcode.com/problems/3sum/). The following is my C code ``` #include "stdlib.h" #include "stdio.h" void bubblesort(int* nums, int numsSize){ for (int i = 0; i < numsSize - 1; i++){ for (int j = 0; j < numsSize - i - 1; j++){ if (nums[j] > nums[j + 1]){ int temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } } int BinarySearch (int *a, int head, int tail, int x){ int left = head, right = tail-1; while (left <= right) { int middle = (left + right)/2; if (x < a[middle]) right = middle - 1; else if (x > a[middle]) left = middle + 1; else return middle; } return -1; } int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int time = 0; bubblesort(nums,numsSize); int** ans = malloc(sizeof(int*)); for(int i = 0;i<numsSize-2;i++){ for(int j = numsSize-1;j>=i+2;j--){ int total = 0 - nums[i] - nums[j]; int index = BinarySearch(nums,i+1,j,total); if(index >= 0){ ans = realloc(ans, sizeof(int*)*(time+1)); ans[time] = (int*) malloc(sizeof(int) * 3); ans[time][0] = nums[i]; ans[time][1] = nums[index]; ans[time][2] = nums[j]; time++; } while(nums[j] == nums[j-1]){ j--; if(j <= i+1) break; } } while(nums[i] == nums[i+1]){ i++; if(i >= numsSize-2) break; } } *returnSize = time; *returnColumnSizes = malloc(sizeof(int*) * (*returnSize)); for (int i = 0; i < (*returnSize); i++) { (*returnColumnSizes)[i] = 3; } return ans; } void printnums(int* nums, int numsSize){ printf("intput : ["); for(int i = 0;i<numsSize;i++){ printf(" %d ",nums[i]); } printf("]\n"); } void printans(int** ans, int* returnSize, int** returnColumnSizes){ for(int i = 0;i<(*returnSize);i++){ printf("output : ["); for(int j = 0;j<(*returnColumnSizes)[i];j++){ printf(" %d ",ans[i][j]); } printf("]\n"); } } int main(){ int nums[] = {-1,0,1,2,-1,4}; int numsSize = 6; printnums(nums,numsSize); int* returnSize = malloc(sizeof(int)); int** returnColumnSizes = malloc(sizeof(int*)); int** ans = threeSum(nums,numsSize,returnSize,returnColumnSizes); printans(ans,returnSize,returnColumnSizes); } ``` ### HW3 assembly code This is my RISC-V assembly code. :::spoiler ``` .data test1:.word -7,-5,3,5,-2,0,1,-1 len1: .word 8 returnSize: .word 0x40000000 returnColumnSize: .word 0x40000100 start_input_line:.string "Input:[" start_output_line:.string "Output:[" endline:.string "]\n" .text main: la a0,test1 lw a1,len1 jal printinput la a0,test1 lw a1,len1 lw a2,returnSize lw a3,returnColumnSize jal threeSum mv a1,a2 mv a2,a3 jal printans j exit printinput: addi sp,sp,-8 sw a0,4(sp) sw ra,0(sp) li t0,0 la a0, start_input_line li a7, 4 ecall printinputloop: slli t1,t0,2 lw s1,4(sp) add s1,s1,t1 lw a0,0(s1) jal printf addi t0,t0,1 blt t0,a1,printinputloop la a0, endline li a7, 4 ecall lw ra,0(sp) addi sp,sp,8 jr ra printans: addi sp,sp,-8 sw a0,4(sp) sw ra,0(sp) lw t5,0(a1) li t3,0 printoutputloop: li t0,0 la a0, start_output_line li a7, 4 ecall lw t4,0(a2) printoutput: slli t1,t0,2 lw s1,4(sp) add s1,s1,t1 lw a0,0(s1) jal printf addi t0,t0,1 blt t0,t4,printoutput la a0, endline li a7, 4 ecall addi a2,a2,4 lw a0,4(sp) addi a0,a0,12 sw a0,4(sp) addi t3,t3,1 blt t3,t5,printoutputloop lw ra,0(sp) addi sp,sp,8 jr ra sort: addi sp,sp,-4 sw a0,0(sp) li t1,0 addi a1,a1,-1 sortloop1: bge t1,a1,done # t1 = i outerloop sub t3,a1,t1 # t3 = numsSize-i-1 li,t2,0 lw a0,0(sp) sortloop2: bge t2,t3,sortloop1done # t2 = j innerloop lw t4,0(a0) # load nums[j] lw t5,4(a0) # load nums[j+1] bge t4,t5,swap j sortloop2done swap: sw t5,0(a0) sw t4,4(a0) sortloop2done: addi a0,a0,4 addi t2,t2,1 j sortloop2 sortloop1done: addi t1,t1,1 j sortloop1 done: lw a0,0(sp) addi sp,sp,4 jr ra BinarySearch: addi sp,sp,-8 sw ra,4(sp) sw a0,0(sp) mv t0,a1 # left = hand addi t1,a2,-1 # tail - 1 Searchloop: lw a0,0(sp) blt t1,t0,BSdone # if right < left go to BSdone add t3,t0,t1 # middle = (left+right)/2 srli t3,t3,1 slli t5,t3,2 add a0,a0,t5 lw t4,0(a0) # a[middle] blt a3,t4, atleft # if a[middle] < x , go to atleft beq a3,t4,get # if a[middle] == x , go to get addi t0,t3,1 j Searchloop atleft: addi t1,t3,-1 j Searchloop get: lw ra,4(sp) addi sp,sp,8 mv a0,t3 jr ra BSdone: lw ra,4(sp) addi sp,sp,8 li t2,-1 mv a0,t2 jr ra threeSum: addi sp,sp,-24 sw a3,20(sp) sw a2,16(sp) sw a1,8(sp) sw ra,4(sp) sw a0,0(sp) li s0,0x20000000 #int** ans sw s0,12(sp) li s1,0 # s1 = time jal sort lw a1,8(sp) li s10,-1 # t4 = i threeSumOuterloop: addi s10,s10,1 addi s9,a1,-2 # s9 = numsSize-2 bge s10,s9,threeSumEnd # if i >= numsSize-2, go to threeSumEnd mv s11,a1 # s11 = numsSize threeSumInnerloop: addi s11,s11,-1 addi t6,s10,2 bge s11,t6,Search # if j >= i+2 go to Search, else go to Outerloop j findOutersame Search: lw a0,0(sp) slli s2,s10,2 add a0,a0,s2 lw s2,0(a0) # s2 = nums[i] lw a0,0(sp) slli s3,s11,2 add a0,a0,s3 lw s3,0(a0) # s3 = nums[j] add s4,s2,s3 sub s4,x0,s4 # s4 = total lw a0,0(sp) addi a1,s10,1 mv a2,s11 mv a3,s4 jal BinarySearch mv s8,a0 # s8 = index lw a0,0(sp) lw a1,8(sp) lw ra,4(sp) bge s8,x0,gettriplets findInnersame: slli s5,s11,2 lw a0,0(sp) add a0,a0,s5 lw s5,0(a0) # s5 = nums[j] lw s6,-4(a0) beq s5,s6,findInner j threeSumInnerloop findInner: addi s11,s11,-1 li s6,1 ble s11,s6,threeSumInnerloop j findInnersame findOutersame: slli s6,s10,2 lw a0,0(sp) add a0,a0,s6 lw s5,0(a0) # s6 = nums[j] lw s6,4(a0) beq s5,s6,findOuter j threeSumOuterloop findOuter: addi s10,s10,1 bgt s10,s9,threeSumOuterloop j findOutersame gettriplets: mv a0,s8 li s7,12 mul s7,s1,s7 lw s0,12(sp) add s0,s0,s7 slli s8,s8,2 lw a0,0(sp) add s8,a0,s8 lw s8,0(s8) # num[index] sw s2,0(s0) sw s8,4(s0) sw s3,8(s0) lw a0,0(sp) addi s1,s1,1 j findInnersame threeSumEnd: lw a3,20(sp) lw a2,16(sp) sw s1,0(a2) li t3,3 columnsize: sw t3,0(a3) addi s1,s1,-1 addi a3,a3,4 li t4,1 bge s1,t4,columnsize lw s0,12(sp) mv a0,s0 lw ra,4(sp) lw a3,20(sp) lw a2,16(sp) addi sp,sp,24 jr ra printf: li a7,1 # print int ecall li a0, 9 # tab li a7, 11 # print char ecall jr ra exit: li a7, 10 # end the program ecall ``` ::: ### HW3 simulation result RTL Simulation result ``` intput : [ -1 3 2 0 -2 -4 3 4 1 0 -3 ] output : [ -4 0 4 ] output : [ -4 1 3 ] output : [ -3 -1 4 ] output : [ -3 0 3 ] output : [ -3 1 2 ] output : [ -2 -1 3 ] output : [ -2 0 2 ] output : [ -1 0 1 ] Excuting 46245 instructions, 61775 cycles, 1.335 CPI Program terminate - ../rtl/../testbench/testbench.v:434: Verilog $finish Simulation statistics ===================== Simulation time : 0.256 s Simulation cycles: 61786 Simulation speed : 0.241352 MHz ``` ISS (Instruction Set Simulator) result ``` ./rvsim --memsize 128 -l trace.log ../sw/hw3_2/hw3_2.elf intput : [ -1 3 2 0 -2 -4 3 4 1 0 -3 ] output : [ -4 0 4 ] output : [ -4 1 3 ] output : [ -3 -1 4 ] output : [ -3 0 3 ] output : [ -3 1 2 ] output : [ -2 -1 3 ] output : [ -2 0 2 ] output : [ -1 0 1 ] Excuting 46245 instructions, 61775 cycles, 1.336 CPI Program terminate Simulation statistics ===================== Simulation time : 0.013 s Simulation cycles: 61775 Simulation speed : 4.861 MHz ``` ## Waveform analysis We can use the following command to create a wave.fst file. ``` sudo apt-get gtkwave # install gtkwave cd srv32/sim make hw3.run cd sim && ./sim +dump ``` Then we can use gtkwave to open the file. ### Analysis ||| IF/ID | EX | WB | | -------- | -------- | -------- |-------- | -------- | | next_pc| fetch_pc (imem_addr)| if_pc |ex_pc|wb_pc| ### Branch Penalty #### branch ``` 20: 0002a023 sw zero,0(t0) 24: 00428293 addi t0,t0,4 28: fe62ece3 bltu t0,t1,20 <_bss_clear> 2c: 00040117 auipc sp,0x40 30: fd410113 addi sp,sp,-44 # 40000 <_stack> 34: 268000ef jal ra,29c <main> 38: 6f41006f j 1072c <exit> ``` First, let discuss how the branch work. In `line 28`, if `t0` > `t1`, it will jump to `line 20`. The `branch_taken` will be set to 1. The following result is from gtkwave. ![](https://i.imgur.com/XbqwHOA.png) If `branch_taken` equal 1, that mean two instructions should be killed. In next clock, it will fetch the correct instruction. | stage | c1 | c2 | c3|c4|c5| | -------- | -------- | -------- |-------- |-------- |-------- | | IF/ID | bltu | auipc | addi (30)|sw|addi (24) | EX | addi | bltu (taken) | NOP|NOP|sw| | WB | sw | addi | bltu|NOP|NOP| #### branch if not taken In `line 28`, if `t0` < `t1`, it will not jump to `line20`. It will go to the next instruction. In `srv32`, branch always fetch next instruction, so it will not kill any instruction ![](https://i.imgur.com/ARjZ9F8.png) | stage | c1 | c2 | c3|c4| | -------- | -------- | -------- |-------- |-------- | | IF/ID | bltu | auipc | addi (30)| jal| | EX | addi | bltu | auipc|addi (30)| | WB | sw | addi | bltu|auipc| #### jump In `line 34` , it will jump to `main` and link `ra`. When execute `jal`, it also set `branch_taken` to 1. That mean two instructions should be killed. ![](https://i.imgur.com/fqrolVl.png) | stage | c1 | c2 | c3|c4| | -------- | -------- | -------- |-------- |-------- | | IF/ID | jal | j | NOP|main| | EX | addi | jal (taken) | NOP|NOP| | WB | auipc | addi | jal|NOP| ### Forwarding We can observe that `auipc` instruction need to pass the value to `addi` and `addi` need to pass the value to `add`. ``` 3f4: 00021997 auipc s3,0x21 3f8: a9c98993 addi s3,s3,-1380 # 20e90 <__malloc_av_> 3fc: 00f987b3 add a5,s3,a5 ``` The following is the result of `gtkwave`. ![](https://i.imgur.com/WKADdpi.png) In this case, We can observe that if instruction need bypass. The previous instruction will transform the value of `ex_result` to `reg_rdata1`. We also can observe that if instruction need bypass, `wb_dst_sel` and `ex_src1_sel` will be the same. The implementation of register forwarding is as follow so we can know how the bypass work. ``` assign reg_rdata1[31: 0] = (ex_src1_sel == 5'h0) ? 32'h0 : (!wb_flush && wb_alu2reg && (wb_dst_sel == ex_src1_sel)) ? // register forwarding (wb_mem2reg ? wb_rdata : wb_result) : regs[ex_src1_sel]; assign reg_rdata2[31: 0] = (ex_src2_sel == 5'h0) ? 32'h0 : (!wb_flush && wb_alu2reg && (wb_dst_sel == ex_src2_sel)) ? // register forwarding (wb_mem2reg ? wb_rdata : wb_result) : regs[ex_src2_sel]; ``` Than we can see there are full bypassing. ## Software optimizations After the analysis of gtkwave, we know that branch will waste two cycle. I try to use `loop unrolling` to reduce cycles. The following is the modified C code. But I find that if the input array size is too small, it will take more cycle to complete it. Because I need some condition to make `loop unrolling` correct. ```diff int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int time = 0; bubblesort(nums,numsSize); int** ans = malloc(sizeof(int*)); for(int i = 0;i<numsSize-2;i++){ for(int j = numsSize-1;j>=i+2;j--){ int total = 0 - nums[i] - nums[j]; int index = BinarySearch(nums,i+1,j,total); if(index >= 0){ ans = realloc(ans, sizeof(int*)*(time+1)); ans[time] = (int*) malloc(sizeof(int) * 3); ans[time][0] = nums[i]; ans[time][1] = nums[index]; ans[time][2] = nums[j]; time++; } while(nums[j] == nums[j-1]){ j--; if(j <= 1) break; } } - while(nums[i] == nums[i+1]){ - i++; - if(i >= numsSize-2) - break; - } + i = i+1; + while(nums[i-1] == nums[i]){ + i++; + if(i >= numsSize-1) + break; + } + if(i >= numsSize-1) + break; + for(int j = numsSize-1;j>=i+2;j--){ + int total = 0 - nums[i] - nums[j]; + int index = BinarySearch(nums,i+1,j,total); + if(index >= 0){ + ans = realloc(ans, sizeof(int*)*(time+1)); + ans[time] = (int*) malloc(sizeof(int) * 3); + ans[time][0] = nums[i]; + ans[time][1] = nums[index]; + ans[time][2] = nums[j]; + time++; + } + while(nums[j] == nums[j-1]){ + j--; + if(j <= i+1) + break; + } + } + while(nums[i] == nums[i+1]){ + i++; + if(i >= numsSize-2) + break; + } } *returnSize = time; *returnColumnSizes = malloc(sizeof(int*) * (*returnSize)); for (int i = 0; i < (*returnSize); i++) { (*returnColumnSizes)[i] = 3; } return ans; } ``` RTL Simulation result ``` intput : [ -1 3 2 0 -2 -4 3 4 1 0 -3 ] output : [ -4 0 4 ] output : [ -4 1 3 ] output : [ -3 -1 4 ] output : [ -3 0 3 ] output : [ -3 1 2 ] output : [ -2 -1 3 ] output : [ -2 0 2 ] output : [ -1 0 1 ] Excuting 46224 instructions, 61746 cycles, 1.335 CPI Program terminate - ../rtl/../testbench/testbench.v:434: Verilog $finish Simulation statistics ===================== Simulation time : 0.256 s Simulation cycles: 61757 Simulation speed : 0.241238 MHz ``` ISS (Instruction Set Simulator) result ``` ./rvsim --memsize 128 -l trace.log ../sw/hw3_2/hw3_2.elf intput : [ -1 3 2 0 -2 -4 3 4 1 0 -3 ] output : [ -4 0 4 ] output : [ -4 1 3 ] output : [ -3 -1 4 ] output : [ -3 0 3 ] output : [ -3 1 2 ] output : [ -2 -1 3 ] output : [ -2 0 2 ] output : [ -1 0 1 ] Excuting 46224 instructions, 61746 cycles, 1.336 CPI Program terminate Simulation statistics ===================== Simulation time : 0.014 s Simulation cycles: 61746 Simulation speed : 4.545 MHz ``` I try to add some code to make the loop as sooner it ends as possible (Add break). It will not jump to another instruction and judge if the loop is complete. ```diff int** threeSum(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int time = 0; bubblesort(nums,numsSize); int** ans = malloc(sizeof(int*)); for(int i = 0;i<numsSize-2;i++){ for(int j = numsSize-1;j>=i+2;j--){ int total = 0 - nums[i] - nums[j]; int index = BinarySearch(nums,i+1,j,total); if(index >= 0){ ans = realloc(ans, sizeof(int*)*(time+1)); ans[time] = (int*) malloc(sizeof(int) * 3); ans[time][0] = nums[i]; ans[time][1] = nums[index]; ans[time][2] = nums[j]; time++; } while(nums[j] == nums[j-1]){ j--; if(j <= i+1) break; } + if(j <= i+1) + break; } i = i +1; while(nums[i-1] == nums[i]){ i++; if(i >= numsSize-1) break; } if(i >= numsSize-1) break; for(int j = numsSize-1;j>=i+2;j--){ int total = 0 - nums[i] - nums[j]; int index = BinarySearch(nums,i+1,j,total); if(index >= 0){ ans = realloc(ans, sizeof(int*)*(time+1)); ans[time] = (int*) malloc(sizeof(int) * 3); ans[time][0] = nums[i]; ans[time][1] = nums[index]; ans[time][2] = nums[j]; time++; } while(nums[j] == nums[j-1]){ j--; if(j <= i+1) break; } + if(j <= i+1) + break; } while(nums[i] == nums[i+1]){ i++; if(i >= numsSize-2) break; } if(i >= numsSize-2) break; } *returnSize = time; *returnColumnSizes = malloc(sizeof(int*) * (*returnSize)); for (int i = 0; i < (*returnSize); i++) { (*returnColumnSizes)[i] = 3; } return ans; } ``` RTL Simulation result ``` intput : [ -1 3 2 0 -2 -4 3 4 1 0 -3 ] output : [ -4 0 4 ] output : [ -4 1 3 ] output : [ -3 -1 4 ] output : [ -3 0 3 ] output : [ -3 1 2 ] output : [ -2 -1 3 ] output : [ -2 0 2 ] output : [ -1 0 1 ] Excuting 46177 instructions, 61701 cycles, 1.336 CPI Program terminate - ../rtl/../testbench/testbench.v:434: Verilog $finish Simulation statistics ===================== Simulation time : 0.254 s Simulation cycles: 61712 Simulation speed : 0.242961 MHz ``` ISS (Instruction Set Simulator) result ``` ./rvsim --memsize 128 -l trace.log ../sw/hw3_2/hw3_2.elf intput : [ -1 3 2 0 -2 -4 3 4 1 0 -3 ] output : [ -4 0 4 ] output : [ -4 1 3 ] output : [ -3 -1 4 ] output : [ -3 0 3 ] output : [ -3 1 2 ] output : [ -2 -1 3 ] output : [ -2 0 2 ] output : [ -1 0 1 ] Excuting 46177 instructions, 61701 cycles, 1.336 CPI Program terminate Simulation statistics ===================== Simulation time : 0.013 s Simulation cycles: 61701 Simulation speed : 4.792 MHz ``` According to these changes, we can save 61775 - 61701 = 74 cycles

    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