is python capable of running on multiple cores?

前端 未结 7 1059
悲&欢浪女
悲&欢浪女 2020-11-28 03:58

Question: Because of python\'s use of \"GIL\" is python capable running its separate threads simultaneously?


Info:

After reading this I came away rathe

7条回答
  •  长情又很酷
    2020-11-28 04:24

    example code taking all 4 cores on my ubuntu 14.04, python 2.7 64 bit.

    import time
    import threading
    
    
    def t():
        with open('/dev/urandom') as f:
            for x in xrange(100):
                f.read(4 * 65535)
    
    if __name__ == '__main__':
        start_time = time.time()
        t()
        t()
        t()
        t()
        print "Sequential run time: %.2f seconds" % (time.time() - start_time)
    
        start_time = time.time()
        t1 = threading.Thread(target=t)
        t2 = threading.Thread(target=t)
        t3 = threading.Thread(target=t)
        t4 = threading.Thread(target=t)
        t1.start()
        t2.start()
        t3.start()
        t4.start()
        t1.join()
        t2.join()
        t3.join()
        t4.join()
        print "Parallel run time: %.2f seconds" % (time.time() - start_time)
    

    result:

    $ python 1.py
    Sequential run time: 3.69 seconds
    Parallel run time: 4.82 seconds
    

提交回复
热议问题