python 突破 GIL 调用lua

首先是致谢,一下是一些参考的文章:

python之ThreadPoolExecutor    https://www.jianshu.com/p/1ed39de60cb6

python结合lua打破GIL的限制    https://blog.csdn.net/q_yang1987/article/details/52240611

 

记录目的(解决的问题):

绕过全局GIL,尽可能多的使用cpu

 

特点:

使用线程池,方便调度管理

使用lua绕过GIL,使得cpu的使用率达到100%

都是脚本语言,上手简单

 

过程:

1. 安装 lupa, pip install lupa

2. 代码

import lupa
import time
from concurrent.futures import ThreadPoolExecutor

# 这里是算pi
lua_code = '''
    function()
        count = 0
        for i = 1, 10000 do
            x = math.random()
            y = math.random()
            if x*x + y*y <= 1 then
                count = count + 1
            end
        end
        return count * 4 /10000
    end
'''

old = time.time()



def wrapper(lua_func):
    return lua_func()

# 创建线程池
p = ThreadPoolExecutor(8)


res = []
# 10000个计算任务
for _ in range(10000):
    res.append(p.submit(lupa.LuaRuntime().eval(lua_code)))
# res 收集到的结果是feature, 需要通过.result获得结果
# 值得注意的是,.result()操作会重新激活GIL,所以要放在最后
res = list(map(lambda x: x.result(), res))

# 线程池可以使用shubmit提交也可以使用map

# lua_funcs = [lupa.LuaRuntime().eval(lua_code) for _ in range(10000)]
# res = list(p.map(wrapper, lua_funcs))

print(time.time() - old)
print(res[0])
print(sum(res)/10000)

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值