您可以使用Python/C API创建Python字符串,这比任何专门使用Python的方法快得多,因为Python本身是在Python/C中实现的。性能可能主要取决于随机数发生器的效率。如果你是一个合理的随机(3)实现的系统,如the one in glibc,高效实现随机字符串应该是这样的:
#include <Python.h>
/* gcc -shared -fpic -O2 -I/usr/include/python2.7 -lpython2.7 rnds.c -o rnds.so */
static PyObject *rnd_string(PyObject *ignore, PyObject *args)
{
const char choices[] = {'0', '1'};
PyObject *s;
char *p, *end;
int size;
if (!PyArg_ParseTuple(args, "i", &size))
return NULL;
// start with a two-char string to avoid the empty string singleton.
if (!(s = PyString_FromString("xx")))
return NULL;
_PyString_Resize(&s, size);
if (!s)
return NULL;
p = PyString_AS_STRING(s);
end = p + size;
for (;;) {
unsigned long rnd = random();
int i = 31; // random() provides 31 bits of randomness
while (i-- > 0 && p < end) {
*p++ = choices[rnd & 1];
rnd >>= 1;
}
if (p == end)
break;
}
return s;
}
static PyMethodDef rnds_methods[] = {
{"rnd_string", rnd_string, METH_VARARGS },
{NULL, NULL, 0, NULL}
};
PyMODINIT_FUNC initrnds(void)
{
Py_InitModule("rnds", rnds_methods);
}
测试此代码哈莱克斯的基准测试显示,它的速度比280X原代码,和2.3倍比哈莱克斯的代码快(我的机器上):
# the above code
>>> t1 = Timer("rnds.rnd_string(2**20)", "import rnds")
>>> sorted(t1.repeat(10,1))
[0.0029861927032470703, 0.0029909610748291016, ...]
# original generator
>>> t2 = Timer("''.join(random.choice('01') for x in xrange(2**20))", "import random")
>>> sorted(t2.repeat(10,1))
[0.8376679420471191, 0.840252161026001, ...]
# halex's generator
>>> t3 = Timer("bin(random.getrandbits(2**20-1))[2:].zfill(2**20-1)", "import random")
>>> sorted(t3.repeat(10,1))
[0.007007122039794922, 0.007027149200439453, ...]
添加C代码到一个项目是一个复杂,但对于关键的操作280X加速,它很可能是值得的。
为了进一步提高效率,请研究更快的RNG,并从不同的线程调用它们,以便并行化并行化随机数生成。后者将受益于无锁同步机制,以确保线程间通信不会妨碍快速生成过程。
非常感谢。 – marshall 2013-04-27 15:34:31
@marshall:你可以使用['b2a_bin(os.urandom(2 ** i/8))'(用Cython写的C扩展)](https://gist.github.com/zed/ 3526111)。请参阅[乘以大数倍的随机()(Python)](http://stackoverflow.com/q/12161988/4279) – jfs 2013-04-28 01:52:49
@ J.F.Sebastian谢谢! – marshall 2013-04-30 18:53:33