# CA_HW3
## Building the environment
### install the verilator and install srv32
We install the verilator to compile Verilog code into C++, We install it by this following step:
`https://verilator.org/guide/latest/install.html`
Next, We build the RISC-V toolchains by x-pack
install lcov
```
sudo apt-get install lcov
```
install NVM
```
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install gcc g++ make
sudo apt-get update && sudo apt-get install yarn
sudo apt install nodejs
sudo apt install build-essential
```
relative pack
```
sudo apt install build-essential ccache
```
```
export CROSS_COMPILE=riscv-none-embed-
```
```
sudo npm install --global xpm@latest
xpm --version
```
```
xpm init # Only at first use.
xpm install @xpack-dev-tools/riscv-none-embed-gcc@latest
```
```
ls -l xpacks/.bin
```
result:

```
cd xpacks/xpack-dev-tools-riscv-none-embed-gcc/.content/bin
```
```
pwd
/home/eecheng/Desktop/srv32/xpacks/xpack-dev-tools-riscv-none-embed-gcc/.content/bin
```
```
export PATH=$PATH:/home/eecheng/Desktop/srv32/xpacks/xpack-dev-tools-riscv-none-embed-gcc/.content/bin
```

Here, we can start to simulation with srv32
## simulation result of srv32
form gtkwave:

## optimization
We change `int` into `volatile int`
```=c
#include <stdio.h>
#include <limits.h>
int maxProfit(int* prices, int pricesSize){
volatile int min_price=INT_MAX;
volatile int p_gap=0;
for (int i=0;i<pricesSize;i++){
if(prices[i]<=min_price)
min_price=prices[i]; //update min_price value
if(prices[i]-min_price>=p_gap)
p_gap=prices[i]-min_price; //update the newest price gap
}
return p_gap;
}
int main(){
int prices[] = {7,1,5,3,6,4};
printf("%d\n", maxProfit(prices,6));
return 0;
}
```
here is the result:
0
Excuting 232 instructions, 420 cycles, 2.92 CPI
Program terminate
- ../rtl/../tb/tb.v:418: Verilog $finish
### Simulation statistics
Simulation time : 0.009 s
Simulation cycles: 528
Simulation speed : 0.07636 MHz
## reference
https://hackmd.io/@eecheng/B1fEgnQwF