看到网上有性能测试 Python 和 node.js,用的斐波那契数列计算,Python 被 nodejs 甩了70多倍,自己用 蒙特卡洛打点计算圆周率测了一遍
test.py 如下:
import time
import math
from random import random
from multiprocessing import Pool
def test(n):
return sum([math.hypot(random(), random()) < 1 for i in range(n)])
def calcPi(nbFutures, tries):
ts = time.time()
p = Pool(4)
result = p.map(test, [tries] * nbFutures)
ret = 4. * sum(result) / float(nbFutures * tries)
span = time.time() - ts
print "time spend ", span
return ret
m = 10000000
if __name__ == '__main__':
print("pi = {}".format(calcPi(2500, 4000)))
print 'done. %f ms' % ((time.time() - tm) * 1000)
Python 迭代1千万次,单进程运行时间 7.841秒,四个进程运行时间 3.306 秒。在四核CPU的笔记本上开更多进程,性能开始下降,就不列数据了。
node.js 代码 test.js:
var sum = 0, m = 10000000;
function hypot(x,y){
return Math.sqrt(x*x + y*y);
}
var tm = Date.now();
for(var i=0;i<m;i++){
if (hypot(Math.random(), Math.random()) < 1){
sum += 1;
}
}
console.log('pi: %j', sum*4/m);
console.log('done. %d ms', Date.now() - tm);
node.js 迭代1千万次,单进程运行多次,时间最低 0.266秒,最高 0.385秒。果然秒杀Python十几倍。
下面用 C 扩展模块进行测试,pimodule.c
#include <stdlib.h>
#include <math.h>
double randf(){
return rand() / (float)RAND_MAX;
}
double calcPi(int x, int y){
srand((unsigned)time(0));
int t = 0, tries = x*y, i;
double a, b;
for(i=0;i<tries;i++){
a = randf();
b = randf();
if (sqrt(a*a + b*b) < 1) t++;
}
return (4.0 * (double)t / (double)tries);
}
Python扩展模块的接口文件 pimodule.i
%module palindrome
%{
#include <stdlib.h>
#include <math.h>
%}
%inline %{
extern float randf();
extern double calcPi(int x, int y);
%}
虽然用的 win7 x64 系统,但是没有使用 VC 编译,使用的 SWIG + MinGW 的 gcc.exe,注意接口文件中函数接口定义必须加上 %inline,否则返回数据不正确
为方便起见,创建一个 build.bat 进行编译
del pimodule.o
del pimodule.py
del pimodule_wrap.c
del pimodule_wrap.o
swig -python pimodule.i
gcc -c pimodule.c -IC:\path\python27\include
gcc -c pimodule_wrap.c -IC:\path\python27\include
gcc -Wall -shared pimodule.o pimodule_wrap.o C:\path\python27\libs\libpython27.a -o _pimodule.pyd
python test.py
编译前修改 test.py,在文件末尾加上
tm = time.time()
print("pi = {}".format(pimodule.calcPi(m, 1)))
print 'done. %f ms' % ((time.time() - tm) * 1000)
Python C 扩展模块测试结果:0.614 秒,还是比 nodejs 慢了一倍,欢迎有兴趣的同学继续优化。