Rust多线程传递给Python是否会被GIL

这篇博客探讨了Rust和Python在多线程性能上的差异。通过创建双线程和三线程的循环计数任务,结果显示Rust的多线程执行速度明显快于Python。Python的多线程在实际运行中表现得更像是串行,而Rust则能实现真正的并行。这表明Rust在处理多线程任务时能更好地保留其原始的性能优势,为Python的多线程优化提供了可能。
摘要由CSDN通过智能技术生成
#[pyfunction]
// 一个双线程,一个三线程,循环级别位10**10(999999999)
pub fn  multi_thread_1(){
    let thread1 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    let thread2 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    thread1.join();
    thread2.join();
}

#[pyfunction]
pub fn  multi_thread_2(){
    let thread1 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    let thread2 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    let thread3 = thread::spawn(||{ let mut a:u128 = 0; loop{ a += 1; if a == 999999999{break;}}});
    thread1.join();
    thread2.join();
    thread3.join();
}

//将上面两个函数打包在一个模块给python
#[pymodule]
// 这一段的传参我有点看不懂,不过是固定模式应该
fn rust_give_python(_py: Python, m: &PyModule) -> PyResult<()>{
    m.add_function(wrap_pyfunction!(multi_thread_1, m)?)?;
    m.add_function(wrap_pyfunction!(multi_thread_2, m)?)?;
    Ok(())
}
[lib]
name = 'rust_give_python'
crate_type = ['cdylib']

[dependencies.pyo3]
version = "0.16.4"
features = ["auto-initialize"]

验证时刻;

import threading

# 这里Python数量级比Rust害小了10倍
def a():
    p: int = 0
    while p < 99999999:
        p += 1


def time_cal(somefuc):
    def fuc(*args):
        a_ = time.time()
        somefuc(*args)
        b_ = time.time()
        print(b_ - a_)
    return fuc

@time_cal
def test1():
    thread1 = threading.Thread(target=a)
    thread2 = threading.Thread(target=a)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()

@time_cal
def test2():
    thread1 = threading.Thread(target=a)
    thread2 = threading.Thread(target=a)
    thread3 = threading.Thread(target=a)
    thread1.start()
    thread2.start()
    thread3.start()
    thread1.join()
    thread2.join()
    thread3.join()



if __name__ == '__main__':
    test1()
    test2()
    a = time.time()
    rust_give_python.multi_thread_1()
    b = time.time()
    rust_give_python.multi_thread_2()
    c = time.time()
    print(b - a, c - b)

结果:
11.623199033737183
17.019014596939087
5.623442649841309 5.721031188964844

这个结果很能说明问题:
11秒秒 和 17相差6,正好是一次循环的次数,说明Python多线程无法搞定并行,是串行的运行。 Rust编译保留了Rust快速的特性,同时时间上相差5.62和5.72,说明是真正的并行。
结论,我们之后可以尝试使用Rust优化Python多线程相关

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值