HYR*_*YRY 2 python ctypes numpy
我想在Python中做一些C语言计算的模拟.例如,unsigned short,single precision float ...
ushort(0xffff) + 1 -> 0
0.1f * 0.1f -> ...
Run Code Online (Sandbox Code Playgroud)
是否有一些库在Python中执行此操作?
我可以使用ctypes来创建unsigned short,single float,但它们不能进行数学运算:
a = c_uint16(0xffff)
b = c_uint16(0x01)
a+b -> TypeError
Run Code Online (Sandbox Code Playgroud)
或者,我可以使用numpy:
>>> np.uint16(0xffff) + np.uint16(0x01)
Warning: overflow encountered in ushort_scalars
0
Run Code Online (Sandbox Code Playgroud)
但与Python的正常计算相比,这是非常缓慢的:
>>> timeit.timeit("a+b", "import numpy as np;a=np.uint16(0xfffe);b=np.uint16(0x01)")
0.35577465681618037
>>> timeit.timeit("0xfffe+0x01")
0.022638104432360251
>>> timeit.timeit("np.uint16(0xfffe) + np.uint16(0x01)", "import numpy as np")
5.904765399236851
Run Code Online (Sandbox Code Playgroud)
编辑:
>>> timeit.timeit("a+b", "a=0xfffe;b=0x01")
0.040062221014295574
Run Code Online (Sandbox Code Playgroud)
编译时0xfffe+0x01,这将被折叠成常量65535.你没有计算加法需要多长时间 - 你只是测量加载常数的时间:
>>> dis.dis(compile("0xfffe+0x01", "", "eval"))
1 0 LOAD_CONST 2 (65535)
3 RETURN_VALUE
Run Code Online (Sandbox Code Playgroud)
尽管如此,添加NumPy标量比添加内置整数要慢,但它不会比纯Python更好.考虑使用Cython - 它将允许您声明类型并以C速度执行计算.或者,尝试在NumPy中矢量化代码(也就是说,如果速度真的很重要).