0

I tend to record the running time of different snippets of code in a single function because this is a training system and repeatedly using one batch of data to test the running time is far from accurate enough. Thus I thing having a class (of anything that fits) to record the time could be super useful. Otherwise I have to get as many variables as the number of snippets I want to test speed for.

I see a great example in the following question. It's simple for testing one round for multiple snippets. However when it comes to average time, I don't think there is a easy fix to that (like adding a global variable). Is there any good solution to this? I think there should be something like every new instance with a same name keep their own variable space?

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

    def __enter__(self):
        self.start = timeit.default_timer()

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

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

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Li haonan
  • 600
  • 1
  • 6
  • 24
  • 1
    It depends how you run this piece of code. Easiest solution: just save it into a file. Then you can write a script that reads file and computes avg – Roim Jul 18 '20 at 19:16
  • @Roim Yeah thx! I think it works and it's better than having a bunch of variables. but also look for more elegant one – Li haonan Jul 18 '20 at 19:45
  • if you like the example that you mentioned, probably you can make an array to save the running time and use class destructor to append the running time into the array – Thulfiqar Jul 18 '20 at 19:50

0 Answers0