How to measure time taken between lines of code in

2019-02-03 22:22发布

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? Something that does this:

import some_time_library

starttime = some_time_library.some_module()
code_tobe_measured() 
endtime = some_time_library.some_module()

time_taken = endtime - starttime

3条回答
The star\"
2楼-- · 2019-02-03 22:34

With a help of a small convenience class, you can measure time spent in indented lines like this:

with CodeTimer():
   line_to_measure()
   another_line()
   # etc...

Which will show the following after the indented line(s) finishes executing:

Code block took: x.xxx ms

The code for above class:

import time

class CodeTimer:
    def __init__(self, name=None):
        self.name = " '"  + name + "'" if name else ''

    def __enter__(self):
        self.start = time.clock()

    def __exit__(self, exc_type, exc_value, traceback):
        self.took = (time.clock() - self.start) * 1000.0
        print('Code block' + self.name + ' took: ' + str(self.took) + ' ms')

You could then name the code blocks you want to measure:

with CodeTimer('loop 1'):
   for i in range(100000):
      pass

with CodeTimer('loop 2'):
   for i in range(100000):
      pass

Code block 'loop 1' took: 4.991 ms
Code block 'loop 2' took: 3.666 ms

And nest them:

with CodeTimer('Outer'):
   for i in range(100000):
      pass

   with CodeTimer('Inner'):
      for i in range(100000):
         pass

   for i in range(100000):
      pass

Code block 'Inner' took: 2.382 ms
Code block 'Outer' took: 10.466 ms
查看更多
干净又极端
3楼-- · 2019-02-03 22:38

You can also use import time library:

start = time.time()
   #your code
end = time.time()
time_taken = end - start
print('Time: ',time_taken)
查看更多
够拽才男人
4楼-- · 2019-02-03 22:41

You can use time.clock for that.

import time
start = time.clock()
#your code here    
print time.clock() - start

First call turns the timer on, and second call tells how many seconds has elapsed.

There are better profiling tools like timeit and profile, however this one will measure the time and this is what your are asking about

查看更多
登录 后发表回答