风-fmgao

导航

GIL线程与进程选择

#!/usr/bin/env python
# encoding: utf-8  
# Date: 2018/6/18


# 计算密集型。应该启动多进程
# from multiprocessing import Process
# from threading import Thread
# import os, time
#
#
# def work():
#     res = 0
#     for i in range(100000000):
#         res *= i
#
#
# if __name__ == '__main__':
#     l = []
#     print(os.cpu_count())  # 8
#     start = time.time()
#     for i in range(8):
#         # p = Process(target=work)  # 耗时10秒多
#         p = Thread(target=work)  # 耗时45.689270973205566
#         l.append(p)
#         p.start()
#     for p in l:
#         p.join()
#     stop = time.time()
#     print('run time is %s ' % (stop - start))

# io密集型,应该使用多线程
from multiprocessing import Process
from threading import Thread
import os, time


def work():
    time.sleep(2)


if __name__ == '__main__':
    l = []
    # print(os.cpu_count())  # 8
    start = time.time()
    for i in range(400):
        p = Process(target=work)  # 12.44145154953003
        # p = Thread(target=work)  # 耗时2.0456738471984863
        l.append(p)
        p.start()
    for p in l:
        p.join()
    stop = time.time()
    print('run time is %s ' % (stop - start))

posted on 2018-06-18 22:39  风-fmgao  阅读(98)  评论(0编辑  收藏  举报