5 Jun 2011

python模仿matlab的tic/toc计时



python模仿matlab的tic/toc计时

python有自己的timeit模块,但是用惯了matlab的tic/toc,模仿了一个,需要用到globals()函数.实现方法如下:

import time
from datetime import datetime

def tic(name=None):
    """start the timer as a dictionary in the global scope"""
    if name is None:
        name = 'MY_TIMER'
    if name in globals():
        globals()[name].append(time.time())
    else:
        globals()[name] = [time.time()]


def toc(s=None, name=None, show=True, show_ms=True):
    """stop the timer and return the elapsed time in seconds, print if show is True"""
    if name is None:
        name = 'MY_TIMER'
    if name not in globals() or len(globals()[name]) == 0:
        return 0.0
    delta_t = time.time() - globals()[name].pop()
    if show:
        s = (s == None or len(s.strip()) == 0) and 'Elapsed time' or s.strip()
        reps = time_format(delta_t, show_ms)
        print(f'{s.strip()}: {delta_t:.3f} seconds - {reps}\n')
    return delta_t


def time_format(t, show_ms=False):
    """format time in seconds to a string in the format HH:MM:SS or HH:MM:SS.mmm"""
    h = int(t // 3600)
    m = int((t - h * 3600) // 60)
    s = int(t - h * 3600 - m * 60)
    reps = f'{h:02d}:{m:02d}:{s:02d}'
    if show_ms:
        ms = int((t - h * 3600 - m * 60 - s) * 1000)
        reps = f'{reps}.{ms:03d}'
    return reps


def get_timestamp():
    """get the current timestamp in the format YYYYMMDDTHHMMSS"""
    the_time = datetime.now()
    the_date = datetime.date(the_time)
    time_string = the_date.strftime('%Y%m%d') + 'T' + the_time.strftime('%H%M%S')
    return time_string

No comments :

Post a Comment