python 筆記,Python隨筆(二)GIL

 2023-10-08 阅读 30 评论 0

摘要:為什么80%的碼農都做不了架構師?>>> ?? GIL(global interpreter lock)是Python一個非常讓人蛋疼的問題,它的存在直接影響了對Python并發線程的性能調優。 這里我搬一個測試出來看看運行時間 from threading import Thread import time times=5 nu

為什么80%的碼農都做不了架構師?>>> ??hot3.png

GIL(global interpreter lock)是Python一個非常讓人蛋疼的問題,它的存在直接影響了對Python并發線程的性能調優。 這里我搬一個測試出來看看運行時間

from threading import Thread
import time
times=5
num=99999999#8個9
def counter():i = 0for _ in range(num):i = i + 1return Truedef 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] = threadfor 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 筆記、[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

轉載于:https://my.oschina.net/VenusV/blog/3030269

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/130090.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息