简体   繁体   中英

most pythonic way to time a loop

So I have a loop which takes a while to run and I wanted to print a rough estimation of the ETA (time required to end), I have written some code to do this but it's quite intricate and I'm sure there must be a cleaner way of doing it, any tip?

my class:

from timeit import default_timer as timer
from datetime import datetime, timedelta
import sys


class Measure:
    def __init__(self):
        self.initial = None
        self.end = None
        self.average = None

    def start_end(self):
        if self.initial is not None:
            self.end = timer()
        else:
            self.initial = timer()

    def avg(self):
        self.start_end()
        if self.end is not None:
            if self.average is None:
                self.average = round((self.end - self.initial), 3)
            else:
                self.average = round((self.average + (self.end - self.initial)) / 2, 3)
            self.initial = timer()

    def avg_time(self):
        self.avg()
        if self.average is not None:
            sys.stdout.write('\r' + "Avg. Time elapsed: " + str(self.average) + " seconds")

    def how_long(self):
        self.start_end()
        if self.end is not None:
            print("Time elapsed: " + str(round((self.end - self.initial), 3)) + " seconds")
            self.initial = timer()

    def estimated_time(self, length):
        self.avg()
        if self.average is not None:
            x = datetime.now() + timedelta(seconds=self.average * length)
            sys.stdout.write('\r' + "I still need to work for at least...: " + str(round(self.average * length, 3))
                             + " seconds. Which means I'll be done by: " + x.strftime("%d/%m/%Y %H:%M:%S"))

You can time any aspect of your code in regards to how long it takes to run, not just a particular chunk of it. But if you want to get just the time taken for the loop itself to compute, you can do something like:

import time

starttime= time.time()

**add your loop/other code here**

endtime= time.time()
print("time elapsed:", endtime - starttime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM