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

相关文章

SQL表间关联查询实例详解

《SQL表间关联查询实例详解》本文主要讲解SQL语句中常用的表间关联查询方式,包括:左连接(leftjoin)、右连接(rightjoin)、全连接(fulljoin)、内连接(innerjoin)、... 目录简介样例准备左外连接右外连接全外连接内连接交叉连接自然连接简介本文主要讲解SQL语句中常用的表

C# WinForms存储过程操作数据库的实例讲解

《C#WinForms存储过程操作数据库的实例讲解》:本文主要介绍C#WinForms存储过程操作数据库的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、存储过程基础二、C# 调用流程1. 数据库连接配置2. 执行存储过程(增删改)3. 查询数据三、事务处

springboot security验证码的登录实例

《springbootsecurity验证码的登录实例》:本文主要介绍springbootsecurity验证码的登录实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录前言代码示例引入依赖定义验证码生成器定义获取验证码及认证接口测试获取验证码登录总结前言在spring

tomcat多实例部署的项目实践

《tomcat多实例部署的项目实践》Tomcat多实例是指在一台设备上运行多个Tomcat服务,这些Tomcat相互独立,本文主要介绍了tomcat多实例部署的项目实践,具有一定的参考价值,感兴趣的可... 目录1.创建项目目录,测试文China编程件2js.创建实例的安装目录3.准备实例的配置文件4.编辑实例的

python+opencv处理颜色之将目标颜色转换实例代码

《python+opencv处理颜色之将目标颜色转换实例代码》OpenCV是一个的跨平台计算机视觉库,可以运行在Linux、Windows和MacOS操作系统上,:本文主要介绍python+ope... 目录下面是代码+ 效果 + 解释转HSV: 关于颜色总是要转HSV的掩膜再标注总结 目标:将红色的部分滤

Spring 中使用反射创建 Bean 实例的几种方式

《Spring中使用反射创建Bean实例的几种方式》文章介绍了在Spring框架中如何使用反射来创建Bean实例,包括使用Class.newInstance()、Constructor.newI... 目录1. 使用 Class.newInstance() (仅限无参构造函数):2. 使用 Construc

MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析

《MyBatis-Plus中Service接口的lambdaUpdate用法及实例分析》本文将详细讲解MyBatis-Plus中的lambdaUpdate用法,并提供丰富的案例来帮助读者更好地理解和应... 目录深入探索MyBATis-Plus中Service接口的lambdaUpdate用法及示例案例背景

MyBatis-Plus中静态工具Db的多种用法及实例分析

《MyBatis-Plus中静态工具Db的多种用法及实例分析》本文将详细讲解MyBatis-Plus中静态工具Db的各种用法,并结合具体案例进行演示和说明,具有很好的参考价值,希望对大家有所帮助,如有... 目录MyBATis-Plus中静态工具Db的多种用法及实例案例背景使用静态工具Db进行数据库操作插入

Spring中@Lazy注解的使用技巧与实例解析

《Spring中@Lazy注解的使用技巧与实例解析》@Lazy注解在Spring框架中用于延迟Bean的初始化,优化应用启动性能,它不仅适用于@Bean和@Component,还可以用于注入点,通过将... 目录一、@Lazy注解的作用(一)延迟Bean的初始化(二)与@Autowired结合使用二、实例解

前端原生js实现拖拽排课效果实例

《前端原生js实现拖拽排课效果实例》:本文主要介绍如何实现一个简单的课程表拖拽功能,通过HTML、CSS和JavaScript的配合,我们实现了课程项的拖拽、放置和显示功能,文中通过实例代码介绍的... 目录1. 效果展示2. 效果分析2.1 关键点2.2 实现方法3. 代码实现3.1 html部分3.2