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

后端 未结 30 1666
甜味超标
甜味超标 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 02:49

    Use line_profiler.

    line_profiler will profile the time individual lines of code take to execute. The profiler is implemented in C via Cython in order to reduce the overhead of profiling.

    from line_profiler import LineProfiler
    import random
    
    def do_stuff(numbers):
        s = sum(numbers)
        l = [numbers[i]/43 for i in range(len(numbers))]
        m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
    
    numbers = [random.randint(1,100) for i in range(1000)]
    lp = LineProfiler()
    lp_wrapper = lp(do_stuff)
    lp_wrapper(numbers)
    lp.print_stats()
    

    The results will be:

    Timer unit: 1e-06 s
    
    Total time: 0.000649 s
    File: 
    Function: do_stuff at line 4
    
    Line #      Hits         Time  Per Hit   % Time  Line Contents
    ==============================================================
         4                                           def do_stuff(numbers):
         5         1           10     10.0      1.5      s = sum(numbers)
         6         1          186    186.0     28.7      l = [numbers[i]/43 for i in range(len(numbers))]
         7         1          453    453.0     69.8      m = ['hello'+str(numbers[i]) for i in range(len(numbers))]
    

提交回复
热议问题