python多线程与c++多线程对比
查了一下说是python对于线程有个全局的大锁GIL。这个互斥锁保护了内存安全,但是将多线程在多核上的并行运算功能也干掉了。
也就是说python的多线程是多个线程交替运行,同一时间只会有一个线程在运行,可以同步推进各项工作,但不能利用多核实现并行运算提高速度。
参考链接: https://www.cnblogs.com/xhnxhnu/p/9728239.html
https://encyclopedia.thefreedictionary.com/Global+interpreter+lock
实际测试:
from threading import Thread
import time
def my_counter():
i = 0
inf = 2147483647
for _ in range(inf):
i = i + 1
return True
def single():
print("顺序运算")
n=6
thread_array = {}
start_time = time.time()
for tid in range(n):
t = Thread(target=my_counter)
print("start")
t.start()
print("join")
t.join()
end_time = time.time()
print("Total time: {}".format(end_time - start_time))
def multi():
print("同步运算")
n=6
thread_array = {}
start_time = time.time()
for tid in range(n):
t = Thread(target=my_counter)
print("start")
t.start()
thread_array[tid] = t
for i in range(n):
print("join")
thread_array[i].join()
end_time = time.time()
print("Total time: {}".format(end_time - start_time))
if __name__ == '__main__':
single()
multi()
运行结果:
D:\python\python_install\python.exe D:/python/python_data/multi_thread_test/main.py
顺序运算
start
join
start
join
start
join
start
join
start
join
start
join
Total time: 496.3798580169678
同步运算
start
start
start
start
start
start
join
join
join
join
join
join
Total time: 496.61106872558594
Process finished with exit code 0
然后我们再来看一下c++的多线程,运行同样功能的程序
// thread.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include<iostream>
#include<thread>
#include<future>
#include<ctime>
using namespace std;
int n = 12;
bool func()
{
int t = 0;
int inf = ~(1<<31);
for (int i = 0; i != inf; i++)
{
t++;
}
return true;
}
void single()
{
cout << "顺序执行" << endl;
clock_t start_t, end_t;
start_t = clock();
vector<future<bool>> v;
for (int i = 0; i != n; i++)
{
v.push_back(async(func));
bool ans = v[i].get();
cout << ans << endl;
}
end_t = clock();
cout << "cost time: " <<double(end_t-start_t)/1000 <<"s"<< endl;
}
void multi()
{
cout << "同时执行" << endl;
clock_t start_t, end_t;
start_t = clock();
vector<future<bool>> v;
for (int i = 0; i != n; i++)
{
v.push_back(async(func));
}
for (int i = 0; i != n; i++)
{
bool ans = v[i].get();
cout << ans << endl;
}
end_t = clock();
cout << "cost time: " << double(end_t-start_t) / 1000 << "s" << endl;
}
int main()
{
single();
multi();
return 0;
}
运行结果:
1
1
1
1
1
1
1
1
1
1
cost time: 20.581s
同时执行
1
1
1
1
1
1
1
1
1
1
1
1
cost time: 3.219s
哎,这天上差地下啊,跟c++一比这python就跟蜗牛一样,艹
估算一下 (496.3798580169678/6) / (20.581/12)
=82.7299763361613/1.715083333333333
=48.23670939390045
也就是说单线程c++的速度要比python快约48倍
(496.61106872558594/6)/(3.219/12)
= 82.76851145426432/0.26825
=308.5499029049928
多线程c++比python快约308倍
下面是我的cpu