【问题标题】:In python, will converting variables to its own type waste CPU power?在 python 中,将变量转换为自己的类型会浪费 CPU 资源吗?
【发布时间】:2014-07-28 03:33:26
【问题描述】:

我正在尝试从数据库中获取一个 int id 编号,并且某些 id 被错误地存储为字符串,我想知道以下哪种方式更好:

# the first method
new_id = int(old_id) + 1
# second
if isinstance(old_id, str):
    new_id = int(old_id) + 1
else:
    new_id = old_id +1

那么问题来了,在 python 中将一个变量转换成它自己的类型需要花费吗?

【问题讨论】:

  • 我认为更好的问题是“类型检查比将类型转换为自身需要更长的时间吗?”
  • 除非您每秒处理数百万个值,否则 CPU 使用率不太可能有明显差异。
  • 无论哪种方法或多或少有效,做这些事情中的任何一个都会挫败任何利用鸭子打字的尝试。我认为两者都是不好的做法。
  • 我认为尝试将来自外部资源的不一致输入转换为一致类型并没有什么坏处。
  • 如果您真的担心 CPU 使用率达到如此纳米级别,那么您一开始就不应该使用 Python。 ;)

标签: python types int


【解决方案1】:

让我们检查一下!

~/Coding >  python -m timeit -s "id1=1;id2='1'" "new_id = int(id1)" "new_id = int(id2)"
1000000 loops, best of 3: 0.755 usec per loop
~/Coding >  python -m timeit -s "id1=1;id2='1';f=lambda x: int(x) if isinstance(x, str) else x" "new_id=f(id1)" "new_id=f(id2)"
1000000 loops, best of 3: 1.15 usec per loop

看起来最有效的方法是简单地进行int 转换而不检查。

我愿意被纠正,这里的问题是 lambda 或我所做的其他事情。

更新: 这实际上可能不是一个公平的答案,因为 if 检查本身比类型转换要快得多。

~/Coding >  python -m timeit "int('3')"
1000000 loops, best of 3: 0.562 usec per loop
~/Coding >  python -m timeit "int(3)"
10000000 loops, best of 3: 0.136 usec per loop
~/Coding >  python -m timeit "if isinstance('3', str): pass"
10000000 loops, best of 3: 0.0966 usec per loop

这意味着这取决于您希望有多少个 id 是字符串,以查看哪个是值得的。

更新 2: 我在这里有点过火了,但我们可以根据您期望拥有多少字符串来确定使用上述时间切换的确切时间。

其中z 是 id 的总数,s 是它们中字符串的百分比,所有值都以微秒为单位,

Always check type: (assuming returning int costs 0 time)
.0966*z + .562*z*s

Always convert without checking:
.136*z*(1-s) + .562*z*s

当我们进行数学运算时,z 和字符串转换被抵消(因为无论如何您都必须转换字符串),我们最终得到以下结果:

s ~= 0.289706

所以看起来 29% 左右的字符串大约是您从一种方法切换到另一种方法的时间。

【讨论】:

  • 在第一个命令行中使用 lambda 与您在第二个命令行中使用的方式相同,应该可以进行公平比较。
猜你喜欢
  • 1970-01-01
  • 2015-05-27
  • 2016-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 2015-01-29
  • 2021-07-15
相关资源
最近更新 更多