推荐学习书目
› 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 · Sep 19, 2022 · 2499 views
    This topic created in 1509 days ago, the information mentioned may be changed or developed.
    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
    yucongo
    Sep 19, 2022❤️1
    1
    试试这个 https://pastebin.ubuntu.com/p/5rWbN3MnrT/
    自然要将 count 改成 id2ent 的赋值……

    文件大的话应该可以提速(内核个数-1 )倍的样子
    passerby233
    passerby233
    Sep 19, 2022❤️1
    2
    for line in rd:
    line = line.strip('\n')
    killva4624
    killva4624
    Sep 19, 2022❤️1
    3
    readlines 会一次性把所有行读进去,换逐行读取。
    zxCoder
    zxCoder
    OP
    Sep 19, 2022
    4
    @killva4624 全读内存里不是会更快吗
    HashV2
    HashV2
    Sep 19, 2022❤️1
    5
    @zxCoder #4 逐行读也会到内存里的,一次加载所有的数据会有 io 问题,如果行与行之间不存在关联逻辑,逐行更好一些
    LindsayZhou
    LindsayZhou
    Sep 19, 2022
    6
    如果性能瓶颈在 json 解析的话,用 ujson: https://github.com/ultrajson/ultrajson
    看 fastapi 的时候找到的库。
    renmu123
    renmu123
    Sep 20, 2022
    7
    起多进程,然后内容平分给每个进程来处理
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4812 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 08:43 · PVG 16:43 · LAX 00:43 · JFK 03:43
    ♥ Do have faith in what you're doing.