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

相关文章

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

mysqld_multi在Linux服务器上运行多个MySQL实例

《mysqld_multi在Linux服务器上运行多个MySQL实例》在Linux系统上使用mysqld_multi来启动和管理多个MySQL实例是一种常见的做法,这种方式允许你在同一台机器上运行多个... 目录1. 安装mysql2. 配置文件示例配置文件3. 创建数据目录4. 启动和管理实例启动所有实例

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

java图像识别工具类(ImageRecognitionUtils)使用实例详解

《java图像识别工具类(ImageRecognitionUtils)使用实例详解》:本文主要介绍如何在Java中使用OpenCV进行图像识别,包括图像加载、预处理、分类、人脸检测和特征提取等步骤... 目录前言1. 图像识别的背景与作用2. 设计目标3. 项目依赖4. 设计与实现 ImageRecogni

Java操作ElasticSearch的实例详解

《Java操作ElasticSearch的实例详解》Elasticsearch是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析等场景,本文将介绍如何在Java应用中使用Elastics... 目录简介环境准备1. 安装 Elasticsearch2. 添加依赖连接 Elasticsearch1. 创

使用C#代码计算数学表达式实例

《使用C#代码计算数学表达式实例》这段文字主要讲述了如何使用C#语言来计算数学表达式,该程序通过使用Dictionary保存变量,定义了运算符优先级,并实现了EvaluateExpression方法来... 目录C#代码计算数学表达式该方法很长,因此我将分段描述下面的代码片段显示了下一步以下代码显示该方法如

Oracle Expdp按条件导出指定表数据的方法实例

《OracleExpdp按条件导出指定表数据的方法实例》:本文主要介绍Oracle的expdp数据泵方式导出特定机构和时间范围的数据,并通过parfile文件进行条件限制和配置,文中通过代码介绍... 目录1.场景描述 2.方案分析3.实验验证 3.1 parfile文件3.2 expdp命令导出4.总结

MySQL的索引失效的原因实例及解决方案

《MySQL的索引失效的原因实例及解决方案》这篇文章主要讨论了MySQL索引失效的常见原因及其解决方案,它涵盖了数据类型不匹配、隐式转换、函数或表达式、范围查询、LIKE查询、OR条件、全表扫描、索引... 目录1. 数据类型不匹配2. 隐式转换3. 函数或表达式4. 范围查询之后的列5. like 查询6

Python开发围棋游戏的实例代码(实现全部功能)

《Python开发围棋游戏的实例代码(实现全部功能)》围棋是一种古老而复杂的策略棋类游戏,起源于中国,已有超过2500年的历史,本文介绍了如何用Python开发一个简单的围棋游戏,实例代码涵盖了游戏的... 目录1. 围棋游戏概述1.1 游戏规则1.2 游戏设计思路2. 环境准备3. 创建棋盘3.1 棋盘类