• 比较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))
    }
    

      

  • 相关阅读:
    494 Target Sum 目标和
    493 Reverse Pairs 翻转对
    492 Construct the Rectangle 构建矩形
    491 Increasing Subsequences 递增子序列
    488 Zuma Game 祖玛游戏
    486 Predict the Winner 预测赢家
    485 Max Consecutive Ones 最大连续1的个数
    483 Smallest Good Base
    Django Form组件
    Django Auth组件
  • 原文地址:https://www.cnblogs.com/ywjcqq/p/14421748.html
Copyright © 2020-2023  润新知