GIL全局锁测试
基础知识:https://www.cnblogs.com/SuKiWX/p/8804974.html
测试环境
python3.7默认解释器(cpython)
cpu为四核
测试代码
#! /usr/bin/python import time from threading import Thread from multiprocessing import Process CPU_NUM = 4 def my_counter(): i = 0 for _ in range(100000000): i = i + 1 return True def test_for_serial(): '''线程依次执行测试''' start_time = time.time() for tid in range(CPU_NUM): t = Thread(target=my_counter) t.start() t.join() end_time = time.time() print("线程依次执行耗时: {}".format(end_time - start_time)) def test_for_concurrent(): '''线程同时执行测试''' ts = [] start_time = time.time() for tid in range(CPU_NUM): t = Thread(target=my_counter) t.start() ts.append(t) for t in ts: t.join() end_time = time.time() print("线程同时执行耗时: {}".format(end_time - start_time)) def test_for_process(base=1): '''进程同时执行''' ts = [] start_time = time.time() for tid in range(CPU_NUM * base): t = Process(target=my_counter) t.start() ts.append(t) for t in ts: t.join() end_time = time.time() print("进程同时执行耗时: {}".format(end_time - start_time)) if __name__ == '__main__': test_for_serial() test_for_concurrent() test_for_process(1)
测试结果
结论
1. 多线程能避开GIL锁
2. 多线程同时执行跟多线程依次执行耗时相差不大,应该是python3.7有改进锁释放提高效率了。别人博客看到py2.7下相差会有百分之三四十,我这边测了几回都是差不多
Become a Linux Programmer