How do I get time of a Python program's execut

2018-12-31 19:31发布

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 module, but it seems it's only for small snippets of code. I want to time the whole program.

标签: python time
25条回答
春风洒进眼中
2楼-- · 2018-12-31 19:47

I really like Paul McGuire's answer, but I use Python3. So for those who are interested: here's a modification of his answer that works with Python 3 on *nix (I imagine, under Windows, that clock() should be used instead of time()):

#python3
import atexit
from time import time, strftime, localtime
from datetime import timedelta

def secondsToStr(elapsed=None):
    if elapsed is None:
        return strftime("%Y-%m-%d %H:%M:%S", localtime())
    else:
        return str(timedelta(seconds=elapsed))

def log(s, elapsed=None):
    line = "="*40
    print(line)
    print(secondsToStr(), '-', s)
    if elapsed:
        print("Elapsed time:", elapsed)
    print(line)
    print()

def endlog():
    end = time()
    elapsed = end-start
    log("End Program", secondsToStr(elapsed))

start = time()
atexit.register(endlog)
log("Start Program")

If you find this useful, you should still up-vote his answer instead of this one, as he did most of the work ;).

查看更多
忆尘夕之涩
3楼-- · 2018-12-31 19:47

I like the output the datetime module provides, where time delta objects show days, hours, minutes etc. as necessary in a human-readable way.

For example:

from datetime import datetime
start_time = datetime.now()
# do your work here
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))

Sample output e.g.

Duration: 0:00:08.309267

or

Duration: 1 day, 1:51:24.269711

Update: As J.F. Sebastian mentioned, this approach might encounter some tricky cases with local time, so it's safer to use:

import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))
查看更多
大哥的爱人
4楼-- · 2018-12-31 19:48

I like Paul McGuire's answer too and came up with a context manager form which suited more my needs.

import datetime as dt
import timeit

class TimingManager(object):
    """Context Manager used with the statement 'with' to time some execution.

    Example:

    with TimingManager() as t:
       # Code to time
    """

    clock = timeit.default_timer

    def __enter__(self):
        """
        """
        self.start = self.clock()
        self.log('\n=> Start Timing: {}')

        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        """
        """
        self.endlog()

        return False

    def log(self, s, elapsed=None):
        """Log current time and elapsed time if present.
        :param s: Text to display, use '{}' to format the text with
            the current time.
        :param elapsed: Elapsed time to display. Dafault: None, no display.
        """
        print s.format(self._secondsToStr(self.clock()))

        if(elapsed is not None):
            print 'Elapsed time: {}\n'.format(elapsed)

    def endlog(self):
        """Log time for the end of execution with elapsed time.
        """
        self.log('=> End Timing: {}', self.now())

    def now(self):
        """Return current elapsed time as hh:mm:ss string.
        :return: String.
        """
        return str(dt.timedelta(seconds = self.clock() - self.start))

    def _secondsToStr(self, sec):
        """Convert timestamp to h:mm:ss string.
        :param sec: Timestamp.
        """
        return str(dt.datetime.fromtimestamp(sec))
查看更多
零度萤火
5楼-- · 2018-12-31 19:53

In Linux or UNIX:

time python yourprogram.py

In Windows, see this Stackoverflow discussion: How to measure execution time of command in windows command line?

查看更多
何处买醉
6楼-- · 2018-12-31 19:55

The time of a Python program's execution measure could be inconsistent depending on:

  • Same program can be evaluated using different algorithms
  • Running time varies between algorithms
  • Running time varies between implementations
  • Running time varies between computers
  • Running time is not predictable based on small inputs

This is because the most effective way is using the "Order of Growth" and learn the Big "O" notation to do it properly, https://en.wikipedia.org/wiki/Big_O_notation

Anyway you can try to evaluate the performance of any Python program in specific machine counting steps per second using this simple algorithm: adapt this to the program you want to evaluate

import time

now = time.time()
future = now + 10
step = 4 # why 4 steps? because until here already 4 operations executed
while time.time() < future:
    step += 3 # why 3 again? because while loop execute 1 comparison and 1 plus equal statement
step += 4 # why 3 more? because 1 comparison starting while when time is over plus final assignment of step + 1 and print statement
print(str(int(step / 10)) + " steps per second")

Hope this help you.

查看更多
墨雨无痕
7楼-- · 2018-12-31 19:57

There is a timeit module which can be used to time the execution times of python codes. It has detailed documentation and examples in python docs (https://docs.python.org/2/library/timeit.html)

查看更多
登录 后发表回答