Python随笔(二)GIL 原

GIL(global interpreter lock)是Python一个非常让人蛋疼的问题,它的存在直接影响了对Python并发线程的性能调优。 这里我搬一个测试出来看看运行时间

from threading import Thread
import time
times=5
num=99999999#8个9
def counter():
    i = 0
    for _ in range(num):
        i = i + 1
    return True

def test_counter_1():
    thread_array = {}
    start_time = time.time()
    for tid in range(times):
        thread = Thread(target=counter)
        thread.start()
        thread.join()
    end_time = time.time()
    print("单线程用时: {}".format(end_time - start_time))
def test_counter_2():
    thread_array = {}
    start_time = time.time()
    for tid in range(times):
        thread = Thread(target=counter)
        thread.start()
        thread_array[tid] = thread
    for i in range(times):
        thread_array[i].join()
    end_time = time.time()
    print("多线程用时: {}".format(end_time - start_time))
if __name__ == '__main__':
    test_counter_1()
    test_counter_2()

test_counter_1是单线程执行五次test_counter_2是5个线程"同时"执行 看看我们的输出

和预想中的不一样,5个线程同时执行,相当于每条线程只执行一次,缺比单线程五次多了整整1S多线程多出了单线程103%的时间 同样的思想我们来看看C++的执行结果

//
// Created by Pulsar on 2019/3/30.
//
#include <pthread.h>
#include <iostream>
#include <ctime>
void *counter(void *arg){
    long long i = 0;
    for(;i<99999999;){
        i+=1;
    }
//    std::cout<<"[INFO] Counter Done"<<std::endl;
    return nullptr;
}
int main(int argc,char **argv){
    clock_t start_time_1,end_time_1,start_time_2,end_time_2;
    start_time_1=clock();
//    单线程多次执行
    for(int i=0;i<5;i+=1){
        counter(nullptr);
    }
    end_time_1=clock();
    std::cout<<"Singal Thread Time:"<<(double)(end_time_1-start_time_1)/CLOCKS_PER_SEC<<std::endl;

//    多线程一次执行
    start_time_2=clock();
    pthread_t thread_id_array[5];
    for(int i=0;i<5;i+=1){
        int error =pthread_create(&thread_id_array[i],NULL,counter,NULL);
        if(error!=0){
            std::cout<<"[INFO] Thread Create Error"<<std::endl;
        }
    }
    for(int i=0;i<5;i+=1){
        pthread_join(thread_id_array[i],NULL);
    }
    end_time_2=clock();
    std::cout<<"Muti Thread Time:"<<(double)(end_time_2-start_time_2)/CLOCKS_PER_SEC<<std::endl;
    getchar();
    return 0;
}

真是令人头秃,没有对比没有伤害

参考文献:

[python中的GIL详解]https://www.cnblogs.com/SuKiWX/p/8804974.html [GlobalInterpreterLock]https://wiki.python.org/moin/GlobalInterpreterLock [python-global-interpreter-lock]https://docs.python.org/3/c-api/init.html#thread-state-and-the-global-interpreter-lock

(adsbygoogle = window.adsbygoogle || []).push({});

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券