繁体   English   中英

Python反向词性能

[英]Python Reverse words performance

我试图在Python中反转单词。 简单的问题(代码)。

解决方案1(20毫秒-99.54%百分位数)

words = reversed([word.strip() for word in words if word != ''])

answer = " ".join(words).strip()

解决方案2(24毫秒-48%百分位数)

words = [word.strip() for word in words if word != '']

answer = " ".join(reversed(words)).strip()

我试图找到这种差异的原因?

使用timeithttps://docs.python.org/3.7/library/timeit.html )运行基准,以查看时间大致相同(对于我猜想的输入示例):

def opt1(words):
  words = reversed([word.strip() for word in words if word != ''])
  answer = " ".join(words).strip()
  return answer

def opt2(words):
  words = [word.strip() for word in words if word != '']
  answer = " ".join(reversed(words)).strip()
  return answer

import timeit, functools

t_opt1 = timeit.Timer(functools.partial(opt1, words))
t_opt2 = timeit.Timer(functools.partial(opt2, words))
# run 5000 times each method:
print('opt1: ', t_opt1.timeit(5000))
print('opt2: ', t_opt2.timeit(5000))

这里唯一的不同是在什么时候临时引用list被丢弃(期间join在第一种情况下,直到在第二种情况下退出函数)。 但这不太重要,除非时序框架以某种方式被破坏(在两种情况下都应包含任何清理时间)。

否则,除非涉及到一些带有奇怪行为的备用解释器,否则两组代码的行为都应相同(操作代码是相同的,除了根据先存储list还是reversed存储而交换顺序外)。 时间差异似乎比其他因素更可能是随机的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM