Get time of execution of a block of code in Python 2.7

后端 未结 6 702
北荒
北荒 2020-12-07 08:52

I would like to measure the time elapsed to evaluate a block of code in a Python program, possibly separating between user cpu time, system cpu time and elapsed time.

<
6条回答
  •  离开以前
    2020-12-07 09:14

    You can achieve this through the Context Manager, for example:

    from contextlib import contextmanager
    import time
    import logging
    @contextmanager
    def _log_time_usage(prefix=""):
        '''log the time usage in a code block
        prefix: the prefix text to show
        '''
        start = time.time()
        try:
            yield
        finally:
            end = time.time()
            elapsed_seconds = float("%.2f" % (end - start))
            logging.debug('%s: elapsed seconds: %s', prefix, elapsed_seconds)
    

    use example:

    with _log_time_usage("sleep 1: "):
        time.sleep(1)
    

提交回复
热议问题