【问题标题】:Python: Creating a function to time the execution of each of the algorithms [duplicate]Python:创建一个函数来计时每个算法的执行[重复]
【发布时间】:2018-04-15 02:08:43
【问题描述】:

三种不同的算法定义如下:

def alg1 (a, b)
  #body

def alg2 (c, d)
  #body

def alg3 (e, f)
  #body

我们希望时间函数执行以下操作:

def timefunc (s1, s2)

    #Start the clock

    #Call one of your algorithms

    #Stop the clock

    #Print the answer and time it took

我这样做了,但它不起作用:

from datetime import datetime 

def timefunc (s1, s2):
   startTime1= datetime.now() 
   alg1(s1, s2)
   timeElapsed1=datetime.now()-startTime1
   print('Time elpased for alg1 '.format(timeElapsed1)) 

   startTime2= datetime.now() 
   alg2(s1,s2)
   timeElapsed2=datetime.now()-startTime2 
   print('Time elpased for alg2 '.format(timeElapsed2)) 

   startTime3= datetime.now() 
   alg3(s1,s2)
   timeElapsed3=datetime.now()-startTime3 
   print('Time elpased for alg3 '.format(timeElapsed3))

请让我知道我做错了什么,或者您是否有更好的方法来做到这一点。谢谢你。

【问题讨论】:

  • 为什么要重新发明轮子而不是使用timeittime 模块?
  • 怎么不工作了?它给出了什么输出?你期待什么输出?你应该发一个minimal reproducible example
  • 如果您至少可以向我们展示错误
  • 使用time.time()作为开始时间和结束时间

标签: python algorithm


【解决方案1】:

您可以使用来自timemodule 的time.time()

【讨论】:

    猜你喜欢
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    • 2014-11-05
    • 2018-06-14
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多