1. 程式人生 > >for 和while 對cpu和內存的影響

for 和while 對cpu和內存的影響

系統性能

關於while for循環的cpu性能以及內存占用情況

同樣的腳本文件,分別使用for和while完成,再用top查看cpu和內存的情況。


[[email protected]]# cat sumwhile.sh

#!/bin/bash

#

declare-i sum=0

declare-i i=1

while [ $i -le 1000000 ];do

letsum+=$i

let i++

done

echo $sum

[[email protected]]# top -b -d 0.1 >>sum_while_top

[[email protected]]# grep 40392 sum_while_top

4039240279 root 20 0 103m 1196 1040 R 95.5 0.1 0:16.36 sumwhile.sh 內存占用情況以及占用cpu的時間

4039240279 root 20 0 103m 1196 1040 R 94.9 0.1 0:16.46 sumwhile.sh

4039240279 root 20 0 103m 1196 1040 R 100.0 0.1 0:16.58 sumwhile.sh

4039240279 root 20 0 103m 1196 1040 R 94.7 0.1 0:16.68 sumwhile.sh

0:00.64sumwhile.sh

[[email protected]]# cat sumfor.sh

#!/bin/bash

#

declare-i sum=0

for i in `seq 1 1000000`; do

letsum+=$i

done

echo $sum

top -b -d0.1 >> sum_for_top

[[email protected]]# grep 40485 sum_for_top

4048540279 root 20 0 201m 99m 1048 R 100.0 10.0 0:43.45 sumfor.sh

4048540279 root 20 0 201m 99m 1048 R 94.7 10.0 0:43.55 sumfor.sh

4048540279 root 20 0 201m 99m 1048 R 95.0 10.0 0:43.65 sumfor.sh

4048540279 root 20 0 201m 99m 1048 R 100.0 10.0 0:43.76 sumfor.sh

4048540279 root 20 0 201m 99m 1048 R 100.0 10.0 0:43.87 sumfor.sh

for循環對內存的占用和對cpu的占用都明顯高於while循環。


求解答原因。


for 和while 對cpu和內存的影響