How to measure time taken between lines of code in python?

前端 未结 7 880
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 11:00

So in Java, we can do How to measure time taken by a function to execute

But how is it done in python? To measure the time start and end time between lines of codes?

相关标签:
7条回答
  • 2020-12-04 12:07

    I was looking for a way how to output a formatted time with minimal code, so here is my solution. Many people use Pandas anyway, so in some cases this can save from additional library imports.

    import pandas as pd
    start = pd.Timestamp.now()
    # code
    print(pd.Timestamp.now()-start)
    

    Output:

    0 days 00:05:32.541600
    

    I would recommend using this if time precision is not the most important, otherwise use time library:

    %timeit pd.Timestamp.now() outputs 3.29 µs ± 214 ns per loop

    %timeit time.time() outputs 154 ns ± 13.3 ns per loop

    0 讨论(0)
提交回复
热议问题