【问题标题】:test performance on different methods of obtaining input in Python测试在 Python 中获取输入的不同方法的性能
【发布时间】:2017-06-08 16:27:05
【问题描述】:

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

1 4 99 8 7

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

方法一:

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

方法二:

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

当用户在测试期间必须与这样的代码进行交互时,如何使用两种不同的方法对代码进行准确的性能检查?有没有有效的方法?

【问题讨论】:

  • 如果这是 Python3,您需要 list(map(...)),因为除非要求,否则 map() 实际上不会计算任何内容。

标签: python input performance-testing


【解决方案1】:

输入时间是恒定的。换成常量字符串不会改变速度差异。

如果你使用timeit模块,要么在语句中用常量替换input(),要么在setup中声明函数 导入时间 随机导入

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

【讨论】:

    【解决方案2】:

    您可以使用 python 的计时函数(导入时间)自己执行此操作,并将 runamount 设置为较大的数字以获得一致的结果。

    total = 0
    
    for i in range(runamount):
        start = time.time()
    
        #your code here    
    
        total += time.time() - start
    return (total / runamount)
    

    对两者都运行它,看看哪个更快,以确定你应该使用哪个。

    【讨论】:

      猜你喜欢
      • 2013-01-31
      • 1970-01-01
      • 2012-12-17
      • 2021-03-24
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      相关资源
      最近更新 更多