本文介绍了比使用`map`功能更快的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个函数f:

def f(x):
    return x**2

,并希望获得一个由f组成的数组,该数组在一定间隔(例如单位间隔(0,1))上求值.我们可以按照以下步骤进行操作:

and want to obtain an array consisting of f evaluated over an interval, for example the unit interval (0,1). We ca do this as follows:

import numpy as np
X = np.arange(0,1,0.01)
arr = np.array(list(map(f, X)))

但是,当函数复杂时(对于我而言,它涉及一些积分),最后一行非常耗时.有没有办法更快地做到这一点?我很高兴有一个非优雅的解决方案-重点是速度.

However, this last line is very time consuming when the function is complicated (in my case it involves some integrals). Is there a way to do this faster? I am happy to have a non-elegant solution - the focus is on speed.

推荐答案

如果f如此复杂,以至于不能用已编译的数组操作来表示,并且只能采用标量,那么我发现可获得最佳性能(相较于显式循环,性能提高了约2倍)

If f is so complicated that it can't be expressed in terms of compiled array operations, and can only take scalars, I have found that frompyfunc gives the best performance (about 2x compared to an explicit loop)

In [76]: def f(x):
    ...:     return x**2
    ...:

In [77]: foo = np.frompyfunc(f,1,1)

In [78]: foo(np.arange(4))
Out[78]: array([0, 1, 4, 9], dtype=object)

In [79]: foo(np.arange(4)).astype(int)
Out[79]: array([0, 1, 4, 9])

它返回dtype对象,因此需要一个astype. np.vectorize也使用此功能,但速度较慢.两者都可以推广到各种形状的输入数组.

It returns dtype object, so needs an astype. np.vectorize uses this as well, but is a bit slower. Both generalize to various shapes of input array(s).

对于一维结果,fromitermap(无list)部分一起使用:

For a 1d result fromiter works with map (without the list) part:

In [84]: np.fromiter((f(x) for x in range(4)),int)
Out[84]: array([0, 1, 4, 9])

In [86]: np.fromiter(map(f, range(4)),int)
Out[86]: array([0, 1, 4, 9])

在实际情况下,您必须自行确定时间.

You'll have to do your own timings in a realistic case.

这篇关于比使用`map`功能更快的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 07:13