java、go、node.js 对于递归程序(如麻将胡牌算法)并发性能对比测试

    技术2022-07-10  110

    1)java

    package Demo07_recursive; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static int f(int i) { if (i <= 1) { return 1; } return f(i - 1) + f(i - 2); } public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2); long start = System.currentTimeMillis(); for (int i = 0; i <= 20; i++) { executorService.submit(new Runnable() { @Override public void run() { int ret = f(45); System.out.println(ret); long end = System.currentTimeMillis(); System.out.println((end - start) * 1.0 / 1000); } }); } executorService.shutdown(); } } /* 1836311903 9.371 1836311903 10.513 1836311903 10.843 1836311903 12.747 1836311903 14.847 1836311903 15.208 1836311903 15.256 1836311903 15.34 1836311903 15.437 1836311903 15.917 1836311903 16.116 1836311903 17.115 1836311903 17.237 1836311903 17.762 1836311903 17.806 1836311903 17.851 1836311903 18.009 1836311903 19.597 1836311903 19.864 1836311903 20.803 1836311903 21.367 */

    从第9s开始有响应,然后直到21s结束

    2)go

    package main import ( "fmt" "runtime" "time" ) func f(i int) int { if i <= 1 { return 1 } return f(i-1) + f(i-2) } func main() { num := runtime.NumCPU() fmt.Println("核心数:", num) runtime.GOMAXPROCS(num) start := time.Now().Second() for i := 0; i <= 20; i++ { go func() { fmt.Println(f(45)) end := time.Now().Second() fmt.Println(start, end, end - start) }() } time.Sleep(time.Second * 100) } /* 核心数: 8 1836311903 0 36 36 1836311903 0 37 37 1836311903 0 37 37 1836311903 0 37 37 1836311903 0 37 37 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 1836311903 0 38 38 */

    go则是大约38s左右才全部完成

    3)node.js

    function f(i){ if (i <= 1){ return 1 } return f(i-1) + f(i-2) } var start = new Date().getTime() for(var i = 0; i <= 20; i++){ console.log(f(45)) var end = new Date().getTime() console.log((end-start)/1000) } /* 1836311903 14.514 1836311903 28.959 1836311903 43.368 1836311903 57.752 1836311903 72.262 1836311903 87.003 1836311903 101.464 1836311903 115.844 1836311903 130.212 1836311903 144.57 1836311903 158.946 1836311903 173.294 1836311903 187.673 1836311903 202.04 1836311903 216.435 1836311903 230.807 1836311903 245.184 1836311903 259.594 1836311903 273.993 1836311903 288.358 1836311903 302.695 */

    总结:

    go是用户级别的线程, java则是内核级别的线程,任务少时真正实现多线程调度。 时间更短。go则是由go专门调度器调度,无法控制。

    node.js除非开多进程,否则单线程只能顺序执行

     

     

     

    Processed: 0.010, SQL: 9