• python 的多线程执行速度


    python 的多线程有点鸡肋,适用场景有局限,单位时间多个核只能跑一个线程。

    有泳池一个,四个泵,但只有一个人,一人只能开启管理着其中一个,所以四个泵没什么用。但是,如果泵的工作时间与冷却恢复时间是1:3(感谢inoahx指出,已改),那么配置的利用率高达100%。
    直接运行代码
    single.py
    #!/usr/bin/python3
    #-*- coding: utf-8 -*-
    # author:zhouchao
    # 功能:直接运行程序 计算时间
    
    import threading
    import sys
    import math
    import time
    
    lists = [];
    for x in range(1,10000000):
        lists.append(x);
    
    
    length = len(lists);
    for x in range(600):
        step = math.ceil(float(length)/600)
        minIndex = step * x
        if minIndex + step > length :
            maxIndex = length
        else:
            maxIndex = minIndex+step
    
        print(lists[minIndex:maxIndex])
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
        fileObject = open("time1.txt",'a+');
        fileObject.write(str(datetime)+"
    ");
        fileObject.close();

    所需时间:134 s

    开600 个线程运行同一代码

    multiThread.py

    #!/usr/bin/python3
    #-*- coding: utf-8 -*-
    # author:zhouchao
    # 功能:600线程计算执行时间
    
    
    import threading
    import sys
    import math
    import time
    
    lists = [];
    for x in range(1,10000000):
        lists.append(x);
    
    
    def function(i):
        global lists
        length = len(lists);
        step = math.ceil(float(length)/600)
        minIndex = step * i
        if minIndex + step > length :
            maxIndex = length
        else:
            maxIndex = minIndex+step
    
        print(lists[minIndex:maxIndex])
        datetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 
        # datetime = str(lists[minIndex:maxIndex])
        fileObject = open("time2.txt",'a+');
        fileObject.write(str(datetime)+"
    ");
        fileObject.close();
    
    
    threads = []
    for i in range(600):
        t = threading.Thread(target=function , args=(i,))
        threads.append(t)
        t.start()
        t.join()

    所需时间:160 s 

  • 相关阅读:
    程序员找工作必备 PHP 基础面试题 (四)
    Laravel 教程:使用Fast Excel解决导出超大 XLSX 文件(千万级)带来的内存问题
    ThinkPHP无限分类的使用
    PHP 的 interface 有什么用处?
    编写可读代码:通过提前返回来减少缩进
    调试事件的派发
    调试对象的构建
    [反汇编分析] 局部变量复用
    [IDA]批量载入结构体
    [反汇编分析]调用函数传入参数不一致时可能寄存器传入参数
  • 原文地址:https://www.cnblogs.com/zc123/p/8469003.html
Copyright © 2020-2023  润新知