Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将整数转换为其字节字符表示形式时的性能_Python_Performance_Python 3.x_Type Conversion - Fatal编程技术网

在python中将整数转换为其字节字符表示形式时的性能

在python中将整数转换为其字节字符表示形式时的性能,python,performance,python-3.x,type-conversion,Python,Performance,Python 3.x,Type Conversion,具体来说,我需要将一个整数,比如说9999,转换成字节,b'9999',在Python2.6到Python3.x中 ('%s'%n).encode() 在Python2.x中,我是这样做的 b'%s'%n 而在Python3.x中 ('%s'%n).encode() Python2.6中的性能 >>> from timeit import Timer >>> Timer('b"%s"%n','n=9999').timeit() 0.24728001750

具体来说,我需要将一个整数,比如说
9999
,转换成字节,
b'9999'
,在Python2.6到Python3.x中

('%s'%n).encode()
在Python2.x中,我是这样做的

b'%s'%n
而在Python3.x中

('%s'%n).encode()
Python2.6中的性能

>>> from timeit import Timer
>>> Timer('b"%s"%n','n=9999').timeit()
0.24728001750963813
python 3.2中的性能

>>> from timeit import Timer
>>> Timer('("%s"%n).encode()','n=9999').timeit()
0.534475012767416
假设我的基准设置正确,在Python3.x中这是一个巨大的损失

有没有办法提高性能以缩小与2.6/2.7的差距

也许通过这条路线

这是我试图优化的生成器函数。它被反复调用,
args
是字符串、字节或数字的列表:

def pack_gen(self, args, encoding='utf-8'):
    crlf = b'\r\n'
    yield ('*%s\r\n'%len(args)).encode(encoding)
    for value in args:
        if not isinstance(value, bytes):
            value = ('%s'%value).encode(encoding)
        yield ('$%s\r\n'%len(value)).encode(encoding)
        yield value
        yield crlf
函数是这样调用的

b''.join(pack_gen(args))

我在Python 3.2中使用repr()得到了更好的结果:

>>> Timer('repr(n).encode()','n=9999').timeit()
0.32432007789611816
>>> Timer('("%s" % n).encode()','n=9999').timeit()
0.44790005683898926
但是,它当然没有
%s”%n
那么灵活

我还检查了Python 3.3.0a3,希望它能稍微加快转换速度,但令人惊讶的是,我得到的结果比3.2中的结果更差:

>>> Timer('repr(n).encode()','n=9999').timeit()
0.35951611599921307
>>> Timer('("%s"%n).encode()','n=9999').timeit()
0.4658188759985933
最后,以下是:

>>> Timer('str(n).encode()','n=9999').timeit()
0.49958825100111426

显示大部分成本可能来自函数调用开销(根据上面的结果,我假设Python实现的
str()
用于整数类型调用
repr()
内部)。因此,如果您需要在这个级别进行优化,那么正如您所建议的,使用cython替换整个代码块可能是一个不错的选择。或者最好向我们展示您正在尝试优化的循环,因为可能有许多其他方法可以加速循环。

为什么需要字节?这是一个巨大的代价,因为您需要先将其转换为字符串,然后再转换为字节。我看不出有什么办法可以解决这个问题。问题是它是否真的相关。在您的应用程序中,这实际上是一个严重的性能损失吗?是的。它位于一个不断被调用的长循环函数中。