没有比较用时,有兴趣的同学可以自己试试。
下边的例子可以看到gevent是单线程下的高并发,在没有DMA异步IO(比如网络通信)的情况下,实际效果和同步的效率一样,甚至可能会更低。
#!/usr/bin/python
from gevent import monkey; monkey.patch_all()
import multiprocessing
import gevent as g
def calc():
x = 0
for i in xrange(2300000000):
x += i
print x
def coroutine():
g.joinall([g.spawn(calc) for x in xrange(24)])
coroutine()
配合多进程将CPU全都跑到100%
#!/usr/bin/python
import multiprocessing
import gevent as g
def calc():
x = 0
for i in xrange(2300000000):
x += i
print x
def coroutine():
g.joinall([g.spawn(calc) for x in xrange(24)])
pool = multiprocessing.Pool(processes = 24)
for h in xrange(24):
pool.apply_async(coroutine)
pool.close()
pool.join()
golang明显更简单,因为go在底层封装了一些异步的函数,所以用起来十分方便,不使用runtime就会单进程在一颗CPU上跑,使用和逻辑CPU相同数目的进程就会把全部CPU跑满,基本上可以说和上边python的协程一样。
package main
import "fmt"
import "runtime"
var ch chan int = make(chan int, 50)
func calc() {
x := 0
for a := 0; a < 2300000000; a++ {
x += a
}
ch <- x
}
func main() {
runtime.GOMAXPROCS(24)
for i := 0; i < 24; i++ {
go calc()
}
for v := range ch {
fmt.Println(v)
if len(ch) <= 0 {
break
}
}
fmt.Println("Done!")
}
/**
*
* __ (__`\
* (__`\ \\`\
* `\\`\ \\ \
* `\\`\ \\ \
* `\\`\#\\ \#
* \_ ##\_ |##
* (___)(___)##
* (0) (0)`\##
* |~ ~ , \##
* | | \##
* | /\ \## __..---'''''-.._.._
* | | \ `\## _.--' _ `.
* Y | \ `##' \`\ \
* / | \ | `\ \
* /_...___| \ | `\\
* / `. | / ##
* | | | / ####
* | | | / ####
* | () () | \ | | _.-' ##
* `. .' `._. |______..| |-'|
* `------' | | | | | || |
* | | | | | || |
* | | | | | || |
* | | | | | || |
* _____ | | | |____| || |
* / `` |-`/ ` |` |
* \________\__\_______\__\
* """"""""" """""""'"""
* Don't be a fucking stupid donkey! No, this is a fucking mule!
*/