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

请问这个代码怎么写能让他跑得更快

  •  
  •   zxCoder · 2022-09-19 13:15:44 +08:00 · 1425 次点击
    这是一个创建于 557 天前的主题,其中的信息可能已经有所发展或是发生改变。
    with open("corpus.jsonl","r") as rd:
        for line in tqdm(rd.readlines()):
            line=line.strip()
            obj=json.loads(line)
            _id=obj["id"]
            id2ent[_id]=obj
    

    这个代码怎么写能让他跑得更快

    yucongo
        1
    yucongo  
       2022-09-19 14:03:24 +08:00   ❤️ 1
    试试这个 https://pastebin.ubuntu.com/p/5rWbN3MnrT/
    自然要将 count 改成 id2ent 的赋值……

    文件大的话应该可以提速(内核个数-1 )倍的样子
    passerby233
        2
    passerby233  
       2022-09-19 15:31:41 +08:00   ❤️ 1
    for line in rd:
    line = line.strip('\n')
    killva4624
        3
    killva4624  
       2022-09-19 19:52:38 +08:00   ❤️ 1
    readlines 会一次性把所有行读进去,换逐行读取。
    zxCoder
        4
    zxCoder  
    OP
       2022-09-19 21:32:46 +08:00
    @killva4624 全读内存里不是会更快吗
    HashV2
        5
    HashV2  
       2022-09-19 22:49:37 +08:00   ❤️ 1
    @zxCoder #4 逐行读也会到内存里的,一次加载所有的数据会有 io 问题,如果行与行之间不存在关联逻辑,逐行更好一些
    LindsayZhou
        6
    LindsayZhou  
       2022-09-19 23:18:46 +08:00
    如果性能瓶颈在 json 解析的话,用 ujson: https://github.com/ultrajson/ultrajson
    看 fastapi 的时候找到的库。
    renmu123
        7
    renmu123  
       2022-09-20 18:16:44 +08:00
    起多进程,然后内容平分给每个进程来处理
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2869 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 11:38 · PVG 19:38 · LAX 04:38 · JFK 07:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.