考虑一下Python 3的输入行,如下所示:
1 4 99 8 7
代码需要将这些输入视为数字,因此设计了以下不同的方式来获取用户的输入或输入:
方法一:
inputLst = [int(i) for i in input().split()]
方法二:
inputLst = map(int, input().split())
当用户在测试期间必须与代码交互时,如何使用两种不同的方法对代码进行准确的性能检查?有没有有效的方法?
答案 0 :(得分:2)
输入时间是恒定的。如果用常量字符串替换它,它不会改变速度的差异。
如果您使用timeit
模块,请在语句中将input()
替换为常量,或在设置中声明该函数
导入时间
随机导入
tests = []
random_input = ' '.join(str(random.randint(1000, 9999)) for _ in range(1000))
setup = 'def input():\n return ' + repr(random_input)
tests.append(timeit.timeit('[int(i) for i in input().split()]', setup, number=10000))
tests.append(timeit.timeit('list(map(int, input().split()))', setup, number=10000))
for i, time in enumerate(tests, 1):
print('Test #{} took {:.3f} seconds to run 10000 trials.'.format(i, time))
输出是哪个(Python2):
Test #1 took 2.477 seconds to run 10000 trials.
Test #2 took 2.079 seconds to run 10000 trials.
(Python3):
Test #1 took 1.448 seconds to run 10000 trials.
Test #2 took 1.152 seconds to run 10000 trials.
所以map()
在两个版本中都确实更快。
答案 1 :(得分:-1)
您可以自己使用python的计时功能(导入时间)并将runamount设置为较高的数字来获得一致的结果。
total = 0
for i in range(runamount):
start = time.time()
#your code here
total += time.time() - start
return (total / runamount)
为它们运行它,看看哪一个更快,找出你应该使用哪个。