zoukankan      html  css  js  c++  java
  • python多线程用法及与单线程耗时比较

    下面,通过一个简单的例子,来把多线程和单线程执行任务的耗时做个比较

    import time
    import threading
    
    # 音乐播放器
    def music(func, loop):
        for i in range(loop):
            print("I was listening to %s the %d time! %s" % (func, i+1, time.time()))
            time.sleep(2)
    
    # 视频播放器
    def movie(func, loop):
        for i in range(loop):
            print("I was watching %s the %d time! %s" % (func, i+1, time.time()))
            time.sleep(5)
    
    
    # 创建线程数组
    threads = []
    
    # 创建线程t1,并添加到线程数组
    t1 = threading.Thread(target=music, args=('十年',2)) # 已经创建好的一个线程
    threads.append(t1) # 追加到线程数组
    
    
    # 创建线程t2,并添加到线程数组
    t2 = threading.Thread(target=movie, args=('疯狂动物城', 2)) # args是一个元组
    threads.append(t2)
    
    
    # 创建线程t3,并添加到线程数组
    # t3 = threading.Thread(target=movie, args=('少林足球', 2))
    # threads.append(t3)
    
    print(threads)
    
    if __name__ == '__main__':
        print("多线程".center(20,'*'))
        start_time = time.time()
        # 启动线程
        for t in threads:
            t.start() # 所有线程启动
        for t in threads:
            t.join() # 守护线程
        end_time = time.time()
        print('开始时间: %s' % start_time)
        print('结束时间: %s' % end_time) #最后的结束时间
        print("总共耗时:{0:.5f}秒".format(end_time - start_time))  # 格式输出耗时
        print('
    ')
        print("单线程".center(20, '*'))
        start_time = time.time()
        music('十年',2)
        movie('疯狂动物城', 2)
        # movie('少林足球', 2)
        end_time = time.time()
        print('开始时间: %s' % start_time)
        print('结束时间: %s' % end_time)  # 最后的结束时间
        print("总共耗时:{0:.5f}秒".format(end_time - start_time))  # 格式输出耗时
    

    多线程增加增加:t3线程

    单线程增加:movie('少林足球', 2)

     

    结论:多线程,增加线程后,运行时间基本上没变,总耗时还是等于耗时最多的线程所花费的时间;单线程则是线性的增加。另外,多线程的启动时间有极微小差异。

  • 相关阅读:
    Codeforces Round #443 (Div. 2)ABC
    Codeforces Round #442 (Div. 2) ABC
    Wannafly挑战赛2 Cut
    热爱工作的蒜蒜
    Codeforces Round #441 (Div. 2) (ABC)
    Codeforces Round #440 (Div. 2)(ABC)
    Codeforces Round #439 (Div. 2)(ABC)
    sphinx 分词搭建手册
    [转]Chrome 控制台console的用法
    shell脚本复制文件夹内容到另外的文件夹,如果存在则自动备份
  • 原文地址:https://www.cnblogs.com/uncleyong/p/6987231.html
Copyright © 2011-2022 走看看