【问题标题】:Python measure elapsed time for code blocks using time.time()Python 使用 time.time() 测量代码块的经过时间
【发布时间】:2016-10-07 14:02:48
【问题描述】:

我正在尝试使用time.time() 来测量代码块的经过时间,

import time
func_time_result = []
t2 = time.time()

for data in data_set:
   data_time = dict()
   t4 = time.time()
   # initialization code for running the function

   try:
      some_function(data)
   except Exception1 as e:
      exception_list.append(e)
   except Exception2 as e:
      exception_list.append(e)
   data_time.data_execution_time = time.time() - t4 # iteration execution time

   func_time_result.append(data_time)

t3 = time.time()
code_block_time_elapsed = t3-t2

time_in_total = dict()
for time in func_time_result:
   for k, v in time.items():
      time_in_total[k] += v

问题是code_block_time_elapsed 不等于data_settime_in_total['data_execution_time'] 中花费的总时间(例如code_block_time_elapsed 通常为210 秒,而data_set 花费的总时间约为150 秒,所以差异约为 60 秒)。我想知道可能的问题是什么?

some_function 与使用bulk.upsert()mongoDB 插入数据有关,data_set 是一个包含 7 个表的列表,每个表有 100k 行。

【问题讨论】:

  • 确切的区别是什么(“非常重要”并不能告诉我们太多)? data_set中的数据结构是什么?为什么要将计时信息存储在time 模块中(在time.data_execution_time 中)?
  • @marcelm 我已经修改了 OP 以详细说明。

标签: mongodb python-3.x time timer


【解决方案1】:

有一个非常好的库,叫做jackedCodeTimerPy,它比时间模块工作得更好。它还具有一些巧妙的错误检查功能,因此您可能想尝试一下。

它提供了非常好的报告,例如

label            min          max         mean        total    run count
-------  -----------  -----------  -----------  -----------  -----------
imports  0.00283813   0.00283813   0.00283813   0.00283813             1
loop     5.96046e-06  1.50204e-05  6.71864e-06  0.000335932           50

我喜欢它如何为您提供有关它的统计信息以及计时器运行的次数。

使用简单。如果我想测量 for 循环中的时间代码,我只需执行以下操作:

from jackedCodeTimerPY import JackedTiming
JTimer = JackedTiming()

for i in range(50):
  JTimer.start('loop')  # 'loop' is the name of the timer
  doSomethingHere = 'This is really useful!'
  JTimer.stop('loop')
print(JTimer.report())  # prints the timing report

您还可以同时运行多个计时器。

JTimer.start('first timer')
JTimer.start('second timer')
do_something = 'amazing'
JTimer.stop('first timer')

do_something = 'else'
JTimer.stop('second timer')

print(JTimer.report())  # prints the timing report

repo 中有更多使用示例。希望这会有所帮助。

https://github.com/BebeSparkelSparkel/jackedCodeTimerPY

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-04-06
    • 2019-05-16
    • 2012-06-29
    • 1970-01-01
    • 2011-11-17
    • 2021-03-01
    • 1970-01-01
    • 2019-12-30
    相关资源
    最近更新 更多