简体   繁体   English

Python反向词性能

[英]Python Reverse words performance

I was trying to reverse words in Python. 我试图在Python中反转单词。 Simple problem (leetcode). 简单的问题(代码)。

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

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

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

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

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

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

I am trying to find the reasoning for this variance? 我试图找到这种差异的原因?

Run a benchmark using timeit ( https://docs.python.org/3.7/library/timeit.html ) to see that the time is more or less the same (for my guessed input sample): 使用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))

The only difference here is in when references to the temporary list are discarded (during join in the first case, not until function exit in the second case). 这里唯一的不同是在什么时候临时引用list被丢弃(期间join在第一种情况下,直到在第二种情况下退出函数)。 But that's unlikely to matter unless the timing framework is broken in some way (it should incorporate any clean up times in both cases). 但这不太重要,除非时序框架以某种方式被破坏(在两种情况下都应包含任何清理时间)。

Otherwise, barring some alternate interpreter with weird behaviors being involved, both sets of code should behave identically (the op codes are identical, aside from swapping the order depending on whether the list is stored first or reversed is called first); 否则,除非涉及到一些带有奇怪行为的备用解释器,否则两组代码的行为都应相同(操作代码是相同的,除了根据先存储list还是reversed存储而交换顺序外)。 timing differences seem more likely to be random than anything else. 时间差异似乎比其他因素更可能是随机的。

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

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