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

同样一块代码为什么在多进程中执行的这么慢啊

  •  
  •   18870715400 · 2020-10-29 22:05:24 +08:00 · 1824 次点击
    这是一个创建于 1247 天前的主题,其中的信息可能已经有所发展或是发生改变。
    import time
    import pymysql
    
    class Result:
        def __init__(self):
            pass
    
        
        def set_result(self, result):
            pass
        
        def set_detail(self, detail):
            pass
        
        def get_json(self):
            pass
    
    first_time = time.time()
    
    conn = pymysql.connect()
    cursor = conn.cursor()
    cursor.execute("sql")
    r = cursor.fetchone()
    res, detail = r[0], r[1]
    
    second_time = time.time()
    
    result = Result()
    result.set_result(res)
    result.set_detail(detail)
    data = result.get_json()
    
    third_time = time.time()
    
    

    在单进程中其中各个时间段的间隔特别短, 也就是当前代码几乎就是秒完成, 但是在 多进程当中, 有时候 second_time 到 third_time 的间隔有的时候竟然会相差 20 多 s, 就是感觉特别奇怪, 有大神有什么方法解决么? 其中 Result 类就是 对 结果进行格式化的, 因该花费不了多少时间. 但是 结果往往相反

    7 条回复    2020-11-01 02:51:46 +08:00
    smallpython
        1
    smallpython  
       2020-10-30 11:54:42 +08:00
    只看你的示例代码看不出来有啥问题, 多进程的示例和 get_json 的示例能贴出来吗
    no1xsyzy
        2
    no1xsyzy  
       2020-10-30 13:58:11 +08:00
    那这显然是 Result 的问题,你全 pass 了让人看啥呢?
    18870715400
        3
    18870715400  
    OP
       2020-10-30 17:35:07 +08:00
    就是因为多进程的原因, 我今天看了日志, 前面的时候跑的挺快的, 但是到后面整个时间越来越长
    18870715400
        4
    18870715400  
    OP
       2020-10-30 18:15:33 +08:00 via Android
    @smallpython
    @no1xsyzy 我查看了日志,主要是因为进程数目超过了电脑核心书目,所以多进程是假的多进程,当程序执行完数据库相关的代码之后跑去执行别的进程之后再回来继续执行,所以时间间隔很长,那么有什么解决的方法呢
    no1xsyzy
        5
    no1xsyzy  
       2020-10-30 19:41:47 +08:00
    @18870715400 进程池…… 不要每一处单独开进程
    多进程是真的多进程,卡到核心数瓶颈了不是多进程本身的问题,是写法或者配置的问题……
    18870715400
        6
    18870715400  
    OP
       2020-10-30 20:17:34 +08:00
    @no1xsyzy 没有办法, 差不多每一项都是单独的功能, 然后该功能单独有多个线程, 没有办法再缩了. 总的大概有 7-9 个进程
    no1xsyzy
        7
    no1xsyzy  
       2020-11-01 02:51:46 +08:00
    不对啊你这要是 CPU 密集不就是这样吗?
    肯定没闲着就是了,
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2815 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:55 · PVG 22:55 · LAX 07:55 · JFK 10:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.