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
SlipStupig
V2EX  ›  Python

关于 Python re 模块和 google re2 模块

  •  
  •   SlipStupig · 2016-02-22 23:08:52 +08:00 · 5013 次点击
    这是一个创建于 2997 天前的主题,其中的信息可能已经有所发展或是发生改变。

    提出一个猜想,挖个坑

    今天对比了一下 python re 和 google 的 re2 , findall 搜索字符串 100 万次 python 需要 57s 左右, re2 大概只需要 11 秒左右(性能测试结果来自 cProfile ),那么现在问题来了, tornado 参数搜索 /无效数据过滤 /还有路由匹配都大量使用了 re ,如果替换成 re2 会有相关的性能提升吗?

    python-re2 : https://pypi.python.org/pypi/re2/
    google re2: https://github.com/google/re2
    BTW :说一下 python-re2 安装方法,先把 github 上的源码先编译安装好,然后用 pip 安装 re2 就行

    第 1 条附言  ·  2016-02-23 15:15:45 +08:00

    测试代码:
    from datetime import date
    import tornado.escape
    import tornado.ioloop
    import tornado.web

    class VersionHandler(tornado.web.RequestHandler):
    def get(self):
    response = { 'version': '3.5.1',
    'last_build': date.today().isoformat() }
    self.write(response)

    class GetGameByIdHandler(tornado.web.RequestHandler):
    def get(self, id):
    response = { 'id': int(id),
    'name': 'Crazy Game',
    'release_date': date.today().isoformat() }
    self.write(response)

    application = tornado.web.Application([
    (r"/getgamebyid/([0-9]+)", GetGameByIdHandler),
    (r"/version", VersionHandler)
    ])

    if name == "main":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

    python-re:
    [server@localhost ~]$ webbench -c 1000 -t 60 -2 --get http://192.168.1.108:8888/getgamebyid/1
    Webbench - Simple Web Benchmark 1.5
    Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

    Benchmarking: GET http://192.168.1.108:8888/getgamebyid/1 (using HTTP/1.1)
    1000 clients, running 60 sec.

    Speed=80840 pages/min, 349074 bytes/sec.
    Requests: 80247 susceed, 593 failed.

    python-re2
    Benchmarking: GET http://192.168.1.108:8888/getgamebyid/1 (using HTTP/1.1)
    1000 clients, running 60 sec.

    Speed=81921 pages/min, 0 bytes/sec.

    Requests: 81430 susceed, 491 failed.

    看起来能得得到小幅度的性能提升,但是 RE2 没有 groupindex 这个对象,会报错,估计得分析一下 pythgon-re2 的源码源码:
    File "/usr/lib64/python2.7/site-packages/tornado/web.py", line 1994, in _find_handler
    if spec.regex.groupindex:
    AttributeError: 're2.Pattern' object has no attribute 'groupindex'

    继续挖坑

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3030 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 15:33 · PVG 23:33 · LAX 08:33 · JFK 11:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.