python - 测试 Python 中获取输入的不同方法的性能

标签 python input performance-testing

考虑 Python 3 的一行输入,如下所示:

1 4 99 8 7

代码需要将这些输入视为数字,因此设计了以下不同的方式来从用户处获取此或类似的输入:

方法一:

inputLst = [int(i) for i in input().split()]

方法二:

inputLst = map(int, input().split())

当用户在测试过程中必须与这样的代码交互时,如何使用两种不同的方法对代码进行准确的性能检查?有什么有效的办法吗?

最佳答案

输入时间是恒定的。如果将其替换为常量字符串,则不会改变速度差异。

如果您使用 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() 在两个版本中确实更快。

关于python - 测试 Python 中获取输入的不同方法的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44441064/

相关文章:

python - 如何在自包含程序中使用 Python 单元测试?

python - 由于 Figsize,x 标签位于我的图形之外

ios - 在 iOS 上放大的输入文本类型

JavaScript 函数构造函数解析安全性

performance-testing - Pharo 系统调整选项

.net - 将 IEnumerable<char> 转换为字符串的最佳方法?

python - 如何更快地使用 Google map 进行地理编码?

python MySQL : Lost connection to MySQL server during query

html - 输入框字体大小不起作用。不知道为什么

machine-learning - ROC 曲线良好,但精确率-召回率曲线较差