Numba让Python和C一样快?

复制代码
# Numba translates Python functions to optimized machine code at runtime using the industry-standard LLVM compiler library.
# Numba-compiled numerical algorithms in Python can approach the speeds of C or FORTRAN. You don't need to replace the 
# Python interpreter, run a separate compilation step, or even have a C/C++ compiler installed. Just apply one of the Numba
# decorators to your Python function, and Numba does the rest. http://numba.pydata.org/

def time_it(func):
    def _(*args, **kwargs):
        import time
        print(str(func).split()[1], 'is running')
        t = time.perf_counter(); r = func(*args, **kwargs)
        t = time.perf_counter() - t
        print(round(t, 3), 'seconds') # print('%.4f' % t)
        return r
    return _

from numba import jit
import random
@time_it
#@jit(nopython=True)
def monte_carlo_pi(nsamples):
    acc = 0
    for i in range(nsamples):
        x = random.random(); y = random.random()
        if (x ** 2 + y ** 2) < 1.0: acc += 1
    return 4.0 * acc / nsamples

print(monte_carlo_pi(1<<21))

# 0.705 seconds 和 1.888 seconds; 2.67倍

# pip install numba
# cp39-win_amd64.whl (2.3 MB)
# cp39-win_amd64.whl (17.0 MB)
# cp39-win_amd64.whl (13.7 MB)
# Successfully installed llvmlite-0.37.0 numba-0.54.1 numpy-1.20.3
# 
# 如果遇到 OSError: Could not load shared object file: llvmlite.dll,
# 先装Visual C++ Redistributable Packages for Visual Studio 2017:
# https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads
# 不行再到这里去下个新轮子,如 llvmlite-0.37.0-cp39-cp39-win_amd64.whl:
# https://www.lfd.uci.edu/~gohlke/pythonlibs/#llvmlite
# pip install --force-reinstall llvmlite-0.37.0-cp39-cp39-win_amd64.whl

# Numba, at the time of writing 0.43.1, only supports simple recursions when the type of the
# arguments don't change between recursions.
@jit(nopython=True)
def simple(n):
    if n == 0: return 1
    return n * simple(n - 1)

print(simple(5))

# Numba has two compilation modes: nopython mode and object mode. The former produces much faster code,
# but has limitations that can force Numba to fall back to the latter. To prevent Numba from falling back,
# and instead raise an error, pass nopython=True.
# https://numba.readthedocs.io/en/stable/user/jit.html
# 还是不行,我的推箱子程序还是很慢。
复制代码

用了全局变量的函数,它就不给JIT. 也许可以假定全局变量都是常量,大胆JIT,出错了后果自负?

posted @   Fun_with_Words  阅读(211)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?









 和4张牌。

点击右上角即可分享
微信分享提示