How do I get time of a Python program's execution?

后端 未结 30 1681
甜味超标
甜味超标 2020-11-22 02:20

I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.

I\'ve looked at the timeit

30条回答
  •  一生所求
    2020-11-22 03:03

    Just use the timeit module. It works with both Python 2 and Python 3.

    import timeit
    
    start = timeit.default_timer()
    
    # All the program statements
    stop = timeit.default_timer()
    execution_time = stop - start
    
    print("Program Executed in "+str(execution_time)) # It returns time in seconds
    

    It returns in seconds and you can have your execution time. It is simple, but you should write these in thew main function which starts program execution. If you want to get the execution time even when you get an error then take your parameter "Start" to it and calculate there like:

    def sample_function(start,**kwargs):
         try:
             # Your statements
         except:
             # except statements run when your statements raise an exception
             stop = timeit.default_timer()
             execution_time = stop - start
             print("Program executed in " + str(execution_time))
    

提交回复
热议问题