python中的str性能 [英] str performance in python

查看:64
本文介绍了python中的str性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在分析一段 python 代码(python 2.63.2)时,我发现str 将对象(在我的例子中是整数)转换为字符串的方法几乎比使用字符串格式慢一个数量级.

这是基准

<预><代码>>>>从 timeit 导入计时器>>>Timer('str(100000)').timeit()0.3145311339386332>>>计时器('"%s"%100000').timeit()0.03803517023435887

有谁知道为什么会这样?我错过了什么吗?

解决方案

'%s' % 100000 由编译器计算,相当于运行时的常量.

<预><代码>>>>导入文件>>>dis.dis(lambda: str(100000))8 0 LOAD_GLOBAL 0 (str)3 LOAD_CONST 1 (100000)6 CALL_FUNCTION 19 RETURN_VALUE>>>dis.dis(lambda: '%s' % 100000)9 0 LOAD_CONST 3 ('100000')3 RETURN_VALUE

带有运行时表达式的

% 并不(显着)比 str 快:

<预><代码>>>>Timer('str(x)', 'x=100').timeit()0.25641703605651855>>>Timer('"%s" % x', 'x=100').timeit()0.2169809341430664

请注意 str 仍然稍微慢一点,正如@DietrichEpp 所说,这是因为 str 涉及查找和函数调用操作,而 % 编译为单个直接字节码:

<预><代码>>>>dis.dis(lambda x: str(x))9 0 LOAD_GLOBAL 0 (str)3 LOAD_FAST 0 (x)6 CALL_FUNCTION 19 RETURN_VALUE>>>dis.dis(lambda x: '%s' % x)10 0 LOAD_CONST 1 ('%s')3 LOAD_FAST 0 (x)6 BINARY_MODULO7 RETURN_VALUE

当然,对于我测试过的系统(CPython 2.7),上述情况是正确的;其他实现可能会有所不同.

While profiling a piece of python code (python 2.6 up to 3.2), I discovered that the str method to convert an object (in my case an integer) to a string is almost an order of magnitude slower than using string formatting.

Here is the benchmark

>>> from timeit import Timer
>>> Timer('str(100000)').timeit()
0.3145311339386332
>>> Timer('"%s"%100000').timeit()
0.03803517023435887

Does anyone know why this is the case? Am I missing something?

解决方案

'%s' % 100000 is evaluated by the compiler and is equivalent to a constant at run-time.

>>> import dis
>>> dis.dis(lambda: str(100000))
  8           0 LOAD_GLOBAL              0 (str)
              3 LOAD_CONST               1 (100000)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE        
>>> dis.dis(lambda: '%s' % 100000)
  9           0 LOAD_CONST               3 ('100000')
              3 RETURN_VALUE        

% with a run-time expression is not (significantly) faster than str:

>>> Timer('str(x)', 'x=100').timeit()
0.25641703605651855
>>> Timer('"%s" % x', 'x=100').timeit()
0.2169809341430664

Do note that str is still slightly slower, as @DietrichEpp said, this is because str involves lookup and function call operations, while % compiles to a single immediate bytecode:

>>> dis.dis(lambda x: str(x))
  9           0 LOAD_GLOBAL              0 (str)
              3 LOAD_FAST                0 (x)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE        
>>> dis.dis(lambda x: '%s' % x)
 10           0 LOAD_CONST               1 ('%s')
              3 LOAD_FAST                0 (x)
              6 BINARY_MODULO       
              7 RETURN_VALUE        

Of course the above is true for the system I tested on (CPython 2.7); other implementations may differ.

这篇关于python中的str性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆