1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pythonで実行時間を計測する

Last updated at Posted at 2019-10-09

背景・問題

time.time()の差分をとる方法で計測すると、返ってくる値が秒数であり、hh:mm:ssの形式になっていない:frowning2:

提案

秒数を見やすい形に変換する関数を自作しました。

from time import time
from contextlib import contextmanager


@contextmanager
def time_counter(label='elapsed time:'):
    """with文で処理の実行時間を測るやつ

    Example
    -------
    >>> from time_counter import time_counter
    >>> from time import sleep
    >>> with time_counter(label='elapsed time:'):
    ...     sleep(.05)
    ...
    elapsed time: 50.9 ms
    """
    t0 = time()
    yield
    t1 = time()
    print(f'{label} {timedelta(seconds=t1 - t0)}')


def timedelta(seconds: float) -> str:
    """1秒未満の場合はミリ秒を表示し、1秒以上の場合はhh:mm:ssの形式にする

    Example
    -------
    >>> from time import time, sleep
    >>> t0 = time()
    >>> sleep(.05)
    >>> t1 = time()
    >>> print(f"elapsed time: {timedelta(t1 - t0)}")
    elapsed time: 51.5 ms
    """
    if seconds < 1:
        return f'{seconds*1000:.3g} ms'
    else:
        m, s = divmod(round(seconds), 60)
        h, m = divmod(m, 60)
        return f'{h:02d}:{m:02d}:{s:02d}'

使用例

from time import sleep

with time_counter():
    sleep(.05)
    y = 1 + 1
print(y)
elapsed time: 50.5 ms
2
1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?