max*_*zig 6 python string python-3.x
假设您想优化在 Python 中实现的(字节)字符串比较密集型算法。由于中央代码路径包含此语句序列
if s < t:
# less than ...
elif t < s:
# greater than ...
else:
# equal ...
Run Code Online (Sandbox Code Playgroud)
将它优化为类似的东西会很棒
r = bytes_compare(s, t)
if r < 0:
# less than ...
elif r > 0:
# greater than ...
else:
# equal ...
Run Code Online (Sandbox Code Playgroud)
其中(假设的)bytes_compare()理想情况下只会调用通常经过优化的三路比较C 函数memcmp()。这会将字符串比较的次数减少一半。除非字符串超短,否则非常可行的优化。
但是如何使用 Python 3 实现呢?
附注:
Python 3 删除了三路比较全局函数cmp()和魔术方法__cmp__()。即使使用 Python 2,bytes该类也没有 __cmp__()成员。
使用该ctypes包可以直接调用,memcmp()但外部函数调用开销ctypes高得令人望而却步。
Python 3(包括 3.6)根本不包含任何对字符串的三向比较支持。尽管丰富的比较运算符等的内部实现__lt__()确实__eq__()调用(在- cf.memcmp()的 C 实现中),但没有可以利用的内部三向比较函数。bytesObjects/bytesobject.c
因此,编写一个通过调用提供三路比较函数的C 扩展memcmp()是下一个最好的事情:
#include <Python.h>
static PyObject* cmp(PyObject* self, PyObject* args) {
PyObject *a = 0, *b = 0;
if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
return 0;
if (!PyBytes_Check(a) || !PyBytes_Check(b)) {
PyErr_SetString(PyExc_TypeError, "only bytes() strings supported");
return 0;
}
Py_ssize_t n = PyBytes_GET_SIZE(a), m = PyBytes_GET_SIZE(b);
char *s = PyBytes_AsString(a), *t = PyBytes_AsString(b);
int r = 0;
if (n == m) {
r = memcmp(s, t, n);
} else if (n < m) {
r = memcmp(s, t, n);
if (!r)
r = -1;
} else {
r = memcmp(s, t, m);
if (!r)
r = 1;
}
return PyLong_FromLong(r);
}
static PyMethodDef bytes_util_methods[] = {
{ "cmp", cmp, METH_VARARGS, "Three way compare 2 bytes() objects." },
{0,0,0,0} };
static struct PyModuleDef bytes_util_def = {
PyModuleDef_HEAD_INIT, "bytes_util", "Three way comparison for strings.",
-1, bytes_util_methods };
PyMODINIT_FUNC PyInit_bytes_util(void) {
Py_Initialize();
return PyModule_Create(&bytes_util_def);
}
Run Code Online (Sandbox Code Playgroud)
编译:
gcc -Wall -O3 -fPIC -shared bytes_util.c -o bytes_util.so -I/usr/include/python3.6m
Run Code Online (Sandbox Code Playgroud)
测试:
>>> import bytes_util
>>> bytes_util.cmp(b'foo', b'barx')
265725
Run Code Online (Sandbox Code Playgroud)
memcmp与通过包调用相比ctypes,此外部调用与内置字节比较运算符具有相同的开销(因为它们也是使用标准 Python 版本作为 C 扩展实现的)。
| 归档时间: |
|
| 查看次数: |
1447 次 |
| 最近记录: |