numba用户手册-11 实例

2024-03-20 09:18
文章标签 实例 用户手册 numba

本文主要是介绍numba用户手册-11 实例,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

numba用户手册

1.numba基础

2.@jit

3.使用自动并行化@jit

4.性能提升

5.创建ufunc

6.@jitclass

7.@cfunc

8.提前编译代码AOT

9.numba线程

10.调试

 

1.19。例子

1.19.1。曼德尔布罗

#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_importfrom timeit import default_timer as timer
from matplotlib.pylab import imshow, jet, show, ion
import numpy as npfrom numba import jit@jit
def mandel(x, y, max_iters):"""Given the real and imaginary parts of a complex number,determine if it is a candidate for membership in the Mandelbrotset given a fixed number of iterations."""i = 0c = complex(x,y)z = 0.0jfor i in range(max_iters):z = z*z + cif (z.real*z.real + z.imag*z.imag) >= 4:return ireturn 255@jit
def create_fractal(min_x, max_x, min_y, max_y, image, iters):height = image.shape[0]width = image.shape[1]pixel_size_x = (max_x - min_x) / widthpixel_size_y = (max_y - min_y) / heightfor x in range(width):real = min_x + x * pixel_size_xfor y in range(height):imag = min_y + y * pixel_size_ycolor = mandel(real, imag, iters)image[y, x] = colorreturn imageimage = np.zeros((500 * 2, 750 * 2), dtype=np.uint8)
s = timer()
create_fractal(-2.0, 1.0, -1.0, 1.0, image, 20)
e = timer()
print(e - s)
imshow(image)
#jet()
#ion()
show()

1.19.2。移动平均

#!/usr/bin/env python
"""
A moving average function using @guvectorize.
"""import numpy as npfrom numba import guvectorize@guvectorize(['void(float64[:], intp[:], float64[:])'], '(n),()->(n)')
def move_mean(a, window_arr, out):window_width = window_arr[0]asum = 0.0count = 0for i in range(window_width):asum += a[i]count += 1out[i] = asum / countfor i in range(window_width, len(a)):asum += a[i] - a[i - window_width]out[i] = asum / countarr = np.arange(20, dtype=np.float64).reshape(2, 10)
print(arr)
print(move_mean(arr, 3))

1.19.3。多线程

下面的代码展示了使用nogil功能时潜在的性能改进。例如,在四核计算机上,我得到以下结果打印出来:

numpy (1 thread)       145 ms
numba (1 thread)       128 ms
numba (4 threads)       35 ms

注意

在Python 3中,您可以使用标准的current.futures模块,而不是手动生成线程并分派任务。

#!/usr/bin/env python
from __future__ import print_function, division, absolute_importimport math
import threading
from timeit import repeatimport numpy as np
from numba import jitnthreads = 4
size = 10**6def func_np(a, b):"""Control function using Numpy."""return np.exp(2.1 * a + 3.2 * b)@jit('void(double[:], double[:], double[:])', nopython=True, nogil=True)
def inner_func_nb(result, a, b):"""Function under test."""for i in range(len(result)):result[i] = math.exp(2.1 * a[i] + 3.2 * b[i])def timefunc(correct, s, func, *args, **kwargs):"""Benchmark *func* and print out its runtime."""print(s.ljust(20), end=" ")# Make sure the function is compiled before we start the benchmarkres = func(*args, **kwargs)if correct is not None:assert np.allclose(res, correct), (res, correct)# time itprint('{:>5.0f} ms'.format(min(repeat(lambda: func(*args, **kwargs),number=5, repeat=2)) * 1000))return resdef make_singlethread(inner_func):"""Run the given function inside a single thread."""def func(*args):length = len(args[0])result = np.empty(length, dtype=np.float64)inner_func(result, *args)return resultreturn funcdef make_multithread(inner_func, numthreads):"""Run the given function inside *numthreads* threads, splitting itsarguments into equal-sized chunks."""def func_mt(*args):length = len(args[0])result = np.empty(length, dtype=np.float64)args = (result,) + argschunklen = (length + numthreads - 1) // numthreads# Create argument tuples for each input chunkchunks = [[arg[i * chunklen:(i + 1) * chunklen] for arg in args]for i in range(numthreads)]# Spawn one thread per chunkthreads = [threading.Thread(target=inner_func, args=chunk)for chunk in chunks]for thread in threads:thread.start()for thread in threads:thread.join()return resultreturn func_mtfunc_nb = make_singlethread(inner_func_nb)
func_nb_mt = make_multithread(inner_func_nb, nthreads)a = np.random.rand(size)
b = np.random.rand(size)correct = timefunc(None, "numpy (1 thread)", func_np, a, b)
timefunc(correct, "numba (1 thread)", func_nb, a, b)
timefunc(correct, "numba (%d threads)" % nthreads, func_nb_mt, a, 

这篇关于numba用户手册-11 实例的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/828986

相关文章

java向微信服务号发送消息的完整步骤实例

《java向微信服务号发送消息的完整步骤实例》:本文主要介绍java向微信服务号发送消息的相关资料,包括申请测试号获取appID/appsecret、关注公众号获取openID、配置消息模板及代码... 目录步骤1. 申请测试系统2. 公众号账号信息3. 关注测试号二维码4. 消息模板接口5. Java测试

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Python实例题之pygame开发打飞机游戏实例代码

《Python实例题之pygame开发打飞机游戏实例代码》对于python的学习者,能够写出一个飞机大战的程序代码,是不是感觉到非常的开心,:本文主要介绍Python实例题之pygame开发打飞机... 目录题目pygame-aircraft-game使用 Pygame 开发的打飞机游戏脚本代码解释初始化部

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

java String.join()方法实例详解

《javaString.join()方法实例详解》String.join()是Java提供的一个实用方法,用于将多个字符串按照指定的分隔符连接成一个字符串,这一方法是Java8中引入的,极大地简化了... 目录bVARxMJava String.join() 方法详解1. 方法定义2. 基本用法2.1 拼接

Linux lvm实例之如何创建一个专用于MySQL数据存储的LVM卷组

《Linuxlvm实例之如何创建一个专用于MySQL数据存储的LVM卷组》:本文主要介绍使用Linux创建一个专用于MySQL数据存储的LVM卷组的实例,具有很好的参考价值,希望对大家有所帮助,... 目录在Centos 7上创建卷China编程组并配置mysql数据目录1. 检查现有磁盘2. 创建物理卷3. 创

Java List排序实例代码详解

《JavaList排序实例代码详解》:本文主要介绍JavaList排序的相关资料,Java排序方法包括自然排序、自定义排序、Lambda简化及多条件排序,实现灵活且代码简洁,文中通过代码介绍的... 目录一、自然排序二、自定义排序规则三、使用 Lambda 表达式简化 Comparator四、多条件排序五、

Java实例化对象的​7种方式详解

《Java实例化对象的​7种方式详解》在Java中,实例化对象的方式有多种,具体取决于场景需求和设计模式,本文整理了7种常用的方法,文中的示例代码讲解详细,有需要的可以了解下... 目录1. ​new 关键字(直接构造)​2. ​反射(Reflection)​​3. ​克隆(Clone)​​4. ​反序列化

Python解决雅努斯问题实例方案详解

《Python解决雅努斯问题实例方案详解》:本文主要介绍Python解决雅努斯问题实例方案,雅努斯问题是指AI生成的3D对象在不同视角下出现不一致性的问题,即从不同角度看物体时,物体的形状会出现不... 目录一、雅努斯简介二、雅努斯问题三、示例代码四、解决方案五、完整解决方案一、雅努斯简介雅努斯(Janu

Python开发文字版随机事件游戏的项目实例

《Python开发文字版随机事件游戏的项目实例》随机事件游戏是一种通过生成不可预测的事件来增强游戏体验的类型,在这篇博文中,我们将使用Python开发一款文字版随机事件游戏,通过这个项目,读者不仅能够... 目录项目概述2.1 游戏概念2.2 游戏特色2.3 目标玩家群体技术选择与环境准备3.1 开发环境3