V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
codingpp
V2EX  ›  Python

刚才测试了一下 Node.js 与 python 的计算性能,震惊了

  •  
  •   codingpp · 2014-05-23 10:10:25 +08:00 · 58294 次点击
    这是一个创建于 3627 天前的主题,其中的信息可能已经有所发展或是发生改变。
    测试脚本之一,是计算40位的斐波那契数列,测试脚本如下:
    node.js
    function fibo (n) {
    return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
    }
    console.log(fibo(40));

    python
    def fibo(n):
    return fibo(n - 1) + fibo(n - 2) if n > 1 else 1
    print fibo(40)

    php
    <?php
    function fibo($n){
    if($n > 1) {
    return fibo($n - 1) + fibo($n - 2);
    } else {
    return 1;
    }
    }
    echo fibo(40);

    测试结果如下:

    node.js
    real 0m3.329s
    user 0m3.318s
    sys 0m0.010s

    python
    real 1m11.325s
    user 1m11.259s
    sys 0m0.015s

    php
    real 1m26.551s
    user 1m26.448s
    sys 0m0.027s


    node.js居然比python快了23倍之多

    之后我又写了一个测试脚本,就是简单的循环
    i = 0
    t = 1
    while(i < 50000000):
    t = t + i
    i += 1
    print t

    node.js居然比python快了70多倍。。比php快了16倍,c语言也比node.js慢了一点点

    虽然也知道python慢,但是这个差的有点多啊
    第 1 条附言  ·  2014-05-23 11:14:58 +08:00
    刚才把程序放到了浏览器中运行,firefox瞬间就返回了,chrome卡了半秒钟也返回了,ie8上直接出不来结果,第二个循环也是一样的。
    楼主比较感兴趣的是v8引擎是如何对递归、循环做优化,使得速度这么快
    105 条回复    2016-04-22 17:23:58 +08:00
    1  2  
    wssgcg1213
        101
    wssgcg1213  
       2014-05-25 23:13:36 +08:00
    编译C/C++模块 node速度虐哭JAVA
    不过大数你就别指望node算了, 双精度二进制浮点数还是有精度瓶颈的
    se77en
        102
    se77en  
       2014-05-26 11:11:03 +08:00
    V8 做了自动 CPS 变换
    se77en
        103
    se77en  
       2014-05-26 11:16:00 +08:00
    zjnjxufe
        104
    zjnjxufe  
       2014-07-16 17:15:55 +08:00
    现在js的引擎比较牛。
    states
        105
    states  
       2016-04-22 17:23:58 +08:00
    # coding=utf-8
    import time


    def fibo(num):
    x, y, z = 0, 0, 1
    yield z
    while x < num:
    x += 1
    y, z = z, y + z
    yield z
    if __name__=="__main__":
    t = time.time()
    for i in fibo(100000):
    pass
    print(time.time() - t)

    1.0970628261566162

    fibo(100000)这个计算完要 1 秒多,呵呵
    1  2  
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2657 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 04:42 · PVG 12:42 · LAX 21:42 · JFK 00:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.