/images/avatar.jpg

草祭の博客

Python全局锁(GIL)

题记

使用threading进行多线程处理的时候,运算速度并没有提高。原因在于python中的全局锁(GIL, global interpreter lock).

样例

计算圆周率的程序

代码

点击展开代码
import threading
import random
import math
import time

def print_run_time(func):
    def wrapper(*args, **kw):
        begin_time = time.time()
        ret = func(*args, **kw)
        end_time = time.time()
        run_time = end_time - begin_time
        print('Run time',run_time)
        return ret
    return wrapper

@print_run_time
def run():
    sample_count = 10000000 #采样次数
    inner = 0 #落在圆内的点
    i = 0
    while i <sample_count:
        x_i = random.uniform(-1,1)
        y_i = random.uniform(-1,1)
        if (math.pow(x_i,2) + math.pow(y_i,2)) < 1:
            inner+=1
        i+=1
    pi = 4*(inner * 1.0)/sample_count
    print(pi)
    
@print_run_time
def single_run():
    print('single','='*20)
    for _ in range(5):
        run()
        
@print_run_time
def multi_run():
    print('multi','='*20)
    ts = []
    for i in range(5):
        ts.append(threading.Thread(target=run))
        ts[i].start()
    for i in range(5):
        ts[i].join()

if __name__ == '__main__':
    multi_run()
    single_run()

结果

~/dataset/xiaoaiKWS/G/code$ python3 测试多线程速度.py

内存层次设计

题记

个人觉得计算机体系结构的内容很散,这里就随便记录一些上课内容.

Point

  1. 现在cpu处理器的速度已经超过内存。多核处理器也加剧了内存的压力.
  2. https://ae01.alicdn.com/kf/H07fb3760040e47119d17b3ca738f8ac4X.jpg
  3. 因为disk读取速度慢,所以页的大小要比块的大小大很多.
  4. 寄存器由编译器来管理。如c=a+b,编译器来分配地址,add $1,$2,$3.
  5. https://ae01.alicdn.com/kf/H1922a3b54a8c45a8a6b2b921ac128061H.jpg
  6. Hit rate(在内存中找数据,能够在上层存储中找到的比率;即cache/(cache+memory))5和Hit time(RAM access time+Time to determine hit/miss)
  7. Miss penalty: time to replace a block from lower level, including time to replace in CPU
  8. 在单CPU串行的情况下,Average memory access time=Hit time + Miss rate * Miss penalty. 在多线程等情况下由多种优化策略,降低Miss penalty对速度的影响,而不简单是这个公式.
  9. https://ae01.alicdn.com/kf/H9bdc2bac5ef2487da9fd9cdb72af0eca9.jpg
  10. https://ae01.alicdn.com/kf/Hda6ea735575e4577a68e26e7cb6d524bv.jpg
  11. 虚拟地址空间被分块,每一块称之为页(page),页表(page table)可以通过虚拟地址索引,页表用于从virtual page numbes映射到physical frames.

参考资料

主存到Cache直接映射、全相联映射和组相联映射 https://blog.csdn.net/dongyanxia1000/article/details/53392315