Golang创建协程与Python创建进程资源消耗

Golang创建协程消耗很少资源,创建协程可以说有点随心所欲,定时多久时间后执行任务可以创建协程,完成某个比较耗时的异步函数可以创建协程等等。

 首先用Python起任务进程,在虚拟机上进程上限200左右,运行所需时间

1532059031.4343863
1532059032.7786460

import os
import time
import multiprocessing
from multiprocessing.dummy import Pool 

def run_task(a,b):
    print('[{}] Task {} pid {} is running, parent pid is {}'.format(time.time(), a ,os.getpid(), os.getppid()))
    result = math_del(a, b)

if __name__ == '__main__':
    print ('Pool processing pid:{}'.format(os.getpid()))
    p = multiprocessing.Pool(processes = 200)
    for i in range(200):
        p.apply_async(run_task, args=(i,i+1,))
    print('Waiting for all subprocess done...')
    time.sleep(5)

再用Golang起协程,起2000协程时间

1532059501.283765916
1532059501.288216636

起2万协程时间

1532059703.026329223
1532059703.083320845

时间在100毫秒以内,

起20万协程时间

1532059840.639819561
1532059842.096952869

时间达到了2秒,可见Golang原生态的协程数量级在千或万级别性能较好。

package main

import (
    "fmt"
    "time"
    "os"
)

func coroutine() {
    cur := time.Now()
    timestamp := cur.UnixNano()
    fmt.Println("start: ", timestamp)

    for i := 1; i <= 2000; i++ {
        go run_task(i)
    }   
    
    cur = time.Now()
    timestamp = cur.UnixNano()
    fmt.Println("end  : ", timestamp)
}

func run_task(i int) {
    fmt.Println(time.Now().UnixNano(), ",Task ", i, " pid ", os.Getpid()," is running, parent pid is ", os.Getppid())
}

func main() {
    go coroutine()
    time.Sleep(2 * time.Second)
    fmt.Println("main terminated")
}

 

你可能感兴趣的:(Golang)