比较php和golang执行速度
统计1-2000000中的素数
php采用的是最版的php7.4
golang采用的是最新版的1.16,开启4个协程
<?php $startTime = time(); $number = 2000000; $primeNumbers = []; for ($i=1;$i<$number;$i++){ if ($i == 1){ $primeNumbers[] = $i; continue; } $flag = true; for ($j=2;$j<$i;$j++){ if ($i % $j == 0){ $flag = false; break; } } if ($flag){ $primeNumbers[] = $i; } } $endTime = time(); echo "progress time = ".($endTime - $startTime)."\n"; echo "prime count =".count($primeNumbers);
package main import ( "fmt" "time" ) func saveData(dataChan chan int){ var number = 2000000 for i:=1;i<number;i++{ dataChan <- i } close(dataChan) } func dealData(dataChan chan int,statusChan chan bool,primeDataChan chan int) { for { value,status := <- dataChan if !status{ statusChan <- true break } flag := false if value == 1{ primeDataChan <- value continue } for i:=2;i<value;i++{ if value % i == 0{ flag = true break } } if !flag{ primeDataChan <- value } } } func main() { var number int = 4 implementTime := time.Now() primeDataChan := make(chan int,2000000) dataChan := make(chan int,1000) statusChan := make(chan bool,4) go saveData(dataChan) for i:=1;i<=number;i++{ go dealData(dataChan,statusChan,primeDataChan) } for i:=1;i<=number;i++{ <- statusChan } fmt.Printf("progress time = %v \n",time.Since(implementTime).Seconds()) fmt.Println("prime count =",len(primeDataChan)) }