无论如何,这对我来说是值得的,所以我会在这里为任何感兴趣的人提出最困难和最不优雅的解决方案。我的解决方案是在 C++ 中实现一个多线程的 min-max in one pass 算法,并使用它来创建一个 Python 扩展模块。这项工作需要一些开销来学习如何使用 Python 和 NumPy C/C++ API,在这里我将展示代码并为希望走这条路的人提供一些小的解释和参考。
多线程最小值/最大值
这里没有什么太有趣的了。数组被分成大小为length / workers 的块。为future 中的每个块计算最小/最大值,然后扫描全局最小值/最大值。
// mt_np.cc
//
// multi-threaded min/max algorithm
#include <algorithm>
#include <future>
#include <vector>
namespace mt_np {
/*
* Get {min,max} in interval [begin,end)
*/
template <typename T> std::pair<T, T> min_max(T *begin, T *end) {
T min{*begin};
T max{*begin};
while (++begin < end) {
if (*begin < min) {
min = *begin;
continue;
} else if (*begin > max) {
max = *begin;
}
}
return {min, max};
}
/*
* get {min,max} in interval [begin,end) using #workers for concurrency
*/
template <typename T>
std::pair<T, T> min_max_mt(T *begin, T *end, int workers) {
const long int chunk_size = std::max((end - begin) / workers, 1l);
std::vector<std::future<std::pair<T, T>>> min_maxes;
// fire up the workers
while (begin < end) {
T *next = std::min(end, begin + chunk_size);
min_maxes.push_back(std::async(min_max<T>, begin, next));
begin = next;
}
// retrieve the results
auto min_max_it = min_maxes.begin();
auto v{min_max_it->get()};
T min{v.first};
T max{v.second};
while (++min_max_it != min_maxes.end()) {
v = min_max_it->get();
min = std::min(min, v.first);
max = std::max(max, v.second);
}
return {min, max};
}
}; // namespace mt_np
Python 扩展模块
这就是事情开始变得丑陋的地方...在 Python 中使用 C++ 代码的一种方法是实现扩展模块。可以使用distutils.core 标准模块构建和安装此模块。 Python 文档中涵盖了这方面的完整描述:https://docs.python.org/3/extending/extending.html。 注意:当然还有其他方法可以获得类似的结果,引用https://docs.python.org/3/extending/index.html#extending-index:
本指南仅涵盖作为此版本 CPython 的一部分提供的用于创建扩展的基本工具。 Cython、cffi、SWIG 和 Numba 等第三方工具提供了更简单和更复杂的方法来为 Python 创建 C 和 C++ 扩展。
从本质上讲,这条路线可能更多的是学术而非实用。话虽如此,我接下来要做的是,非常接近教程,创建一个模块文件。这本质上是 distutils 知道如何处理您的代码并从中创建 Python 模块的样板。在执行任何这些操作之前,最好先创建一个 Python 虚拟环境,这样您就不会污染您的系统包(参见 https://docs.python.org/3/library/venv.html#module-venv)。
这是模块文件:
// mt_np_forpy.cc
//
// C++ module implementation for multi-threaded min/max for np
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#include <python3.6/numpy/arrayobject.h>
#include "mt_np.h"
#include <cstdint>
#include <iostream>
using namespace std;
/*
* check:
* shape
* stride
* data_type
* byteorder
* alignment
*/
static bool check_array(PyArrayObject *arr) {
if (PyArray_NDIM(arr) != 1) {
PyErr_SetString(PyExc_RuntimeError, "Wrong shape, require (1,n)");
return false;
}
if (PyArray_STRIDES(arr)[0] != 8) {
PyErr_SetString(PyExc_RuntimeError, "Expected stride of 8");
return false;
}
PyArray_Descr *descr = PyArray_DESCR(arr);
if (descr->type != NPY_LONGLTR && descr->type != NPY_DOUBLELTR) {
PyErr_SetString(PyExc_RuntimeError, "Wrong type, require l or d");
return false;
}
if (descr->byteorder != '=') {
PyErr_SetString(PyExc_RuntimeError, "Expected native byteorder");
return false;
}
if (descr->alignment != 8) {
cerr << "alignment: " << descr->alignment << endl;
PyErr_SetString(PyExc_RuntimeError, "Require proper alignement");
return false;
}
return true;
}
template <typename T>
static PyObject *mt_np_minmax_dispatch(PyArrayObject *arr) {
npy_intp size = PyArray_SHAPE(arr)[0];
T *begin = (T *)PyArray_DATA(arr);
auto minmax =
mt_np::min_max_mt(begin, begin + size, thread::hardware_concurrency());
return Py_BuildValue("(L,L)", minmax.first, minmax.second);
}
static PyObject *mt_np_minmax(PyObject *self, PyObject *args) {
PyArrayObject *arr;
if (!PyArg_ParseTuple(args, "O", &arr))
return NULL;
if (!check_array(arr))
return NULL;
switch (PyArray_DESCR(arr)->type) {
case NPY_LONGLTR: {
return mt_np_minmax_dispatch<int64_t>(arr);
} break;
case NPY_DOUBLELTR: {
return mt_np_minmax_dispatch<double>(arr);
} break;
default: {
PyErr_SetString(PyExc_RuntimeError, "Unknown error");
return NULL;
}
}
}
static PyObject *get_concurrency(PyObject *self, PyObject *args) {
return Py_BuildValue("I", thread::hardware_concurrency());
}
static PyMethodDef mt_np_Methods[] = {
{"mt_np_minmax", mt_np_minmax, METH_VARARGS, "multi-threaded np min/max"},
{"get_concurrency", get_concurrency, METH_VARARGS,
"retrieve thread::hardware_concurrency()"},
{NULL, NULL, 0, NULL} /* sentinel */
};
static struct PyModuleDef mt_np_module = {PyModuleDef_HEAD_INIT, "mt_np", NULL,
-1, mt_np_Methods};
PyMODINIT_FUNC PyInit_mt_np() { return PyModule_Create(&mt_np_module); }
在此文件中,大量使用了 Python 以及 NumPy API,有关更多信息,请参阅:https://docs.python.org/3/c-api/arg.html#c.PyArg_ParseTuple,对于 NumPy:https://docs.scipy.org/doc/numpy/reference/c-api.array.html。
安装模块
接下来要做的是利用 distutils 安装模块。这需要一个设置文件:
# setup.py
from distutils.core import setup,Extension
module = Extension('mt_np', sources = ['mt_np_module.cc'])
setup (name = 'mt_np',
version = '1.0',
description = 'multi-threaded min/max for np arrays',
ext_modules = [module])
要最终安装模块,请在您的虚拟环境中执行python3 setup.py install。
测试模块
最后,我们可以测试一下 C++ 实现是否真的优于 NumPy 的幼稚使用。为此,这里有一个简单的测试脚本:
# timing.py
# compare numpy min/max vs multi-threaded min/max
import numpy as np
import mt_np
import timeit
def normal_min_max(X):
return (np.min(X),np.max(X))
print(mt_np.get_concurrency())
for ssize in np.logspace(3,8,6):
size = int(ssize)
print('********************')
print('sample size:', size)
print('********************')
samples = np.random.normal(0,50,(2,size))
for sample in samples:
print('np:', timeit.timeit('normal_min_max(sample)',
globals=globals(),number=10))
print('mt:', timeit.timeit('mt_np.mt_np_minmax(sample)',
globals=globals(),number=10))
这是我做这一切的结果:
8
********************
sample size: 1000
********************
np: 0.00012079699808964506
mt: 0.002468645994667895
np: 0.00011947099847020581
mt: 0.0020772050047526136
********************
sample size: 10000
********************
np: 0.00024697799381101504
mt: 0.002037393998762127
np: 0.0002713389985729009
mt: 0.0020942929986631498
********************
sample size: 100000
********************
np: 0.0007130410012905486
mt: 0.0019842900001094677
np: 0.0007540129954577424
mt: 0.0029724110063398257
********************
sample size: 1000000
********************
np: 0.0094779249993735
mt: 0.007134920000680722
np: 0.009129883001151029
mt: 0.012836456997320056
********************
sample size: 10000000
********************
np: 0.09471094200125663
mt: 0.0453535050037317
np: 0.09436299200024223
mt: 0.04188535599678289
********************
sample size: 100000000
********************
np: 0.9537652180006262
mt: 0.3957935369980987
np: 0.9624398809974082
mt: 0.4019058070043684
这些结果远没有线程前面显示的结果那么令人鼓舞,结果表明速度提高了大约 3.5 倍,并且没有包含多线程。我取得的结果在一定程度上是合理的,我预计线程的开销将占主导地位,直到数组变得非常大,此时性能提升将开始接近std::thread::hardware_concurrency x 增加。
结论
似乎对某些 NumPy 代码进行特定于应用程序的优化确实有空间,尤其是在多线程方面。我不清楚这是否值得努力,但它确实似乎是一个很好的练习(或其他东西)。我认为也许学习一些像 Cython 这样的“第三方工具”可能会更好地利用时间,但谁知道呢。