我有一个长度为20个字节的字符串,我想将它转换为
有没有方法可以避免从str到bytearray的深层复制,以便进行类型转换?或者,是否可以使用像memoryview这样的技术将字符串转换为bytearray而不进行深拷贝?我正在使用Python 2.7。
性能结果:
使用eryksun和Brian Larsen的建议,在一个带有Ubuntu 12.04和Python 2.7的vbox VM下进行基准测试。
- method1使用我的原始帖子 - method2使用ctype from_buffer_copy - method3使用ctype cast/POINTER - method4使用numpy
结果:
- method1需要3.87秒 - method2需要0.42秒 - method3需要1.44秒 - method4需要8.79秒
代码:
ctypes.c_ubyte
数组以便进行位域操作。 import ctypes
str_bytes = '01234567890123456789'
byte_arr = bytearray(str_bytes)
raw_bytes = (ctypes.c_ubyte*20)(*(byte_arr))
有没有方法可以避免从str到bytearray的深层复制,以便进行类型转换?或者,是否可以使用像memoryview这样的技术将字符串转换为bytearray而不进行深拷贝?我正在使用Python 2.7。
性能结果:
使用eryksun和Brian Larsen的建议,在一个带有Ubuntu 12.04和Python 2.7的vbox VM下进行基准测试。
- method1使用我的原始帖子 - method2使用ctype from_buffer_copy - method3使用ctype cast/POINTER - method4使用numpy
结果:
- method1需要3.87秒 - method2需要0.42秒 - method3需要1.44秒 - method4需要8.79秒
代码:
import ctypes
import time
import numpy
str_bytes = '01234567890123456789'
def method1():
result = ''
t0 = time.clock()
for x in xrange(0,1000000):
byte_arr = bytearray(str_bytes)
result = (ctypes.c_ubyte*20)(*(byte_arr))
t1 = time.clock()
print(t1-t0)
return result
def method2():
result = ''
t0 = time.clock()
for x in xrange(0,1000000):
result = (ctypes.c_ubyte * 20).from_buffer_copy(str_bytes)
t1 = time.clock()
print(t1-t0)
return result
def method3():
result = ''
t0 = time.clock()
for x in xrange(0,1000000):
result = ctypes.cast(str_bytes, ctypes.POINTER(ctypes.c_ubyte * 20))[0]
t1 = time.clock()
print(t1-t0)
return result
def method4():
result = ''
t0 = time.clock()
for x in xrange(0,1000000):
arr = numpy.asarray(str_bytes)
result = arr.ctypes.data_as(ctypes.POINTER(ctypes.c_ubyte*len(str_bytes)))
t1 = time.clock()
print(t1-t0)
return result
print(method1())
print(method2())
print(method3())
print(method4())