使用“时间"模块测量经过时间 [英] Measuring elapsed time with the Time module

查看:144
本文介绍了使用“时间"模块测量经过时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python中的时间"模块,可以测量经过的时间吗?如果是这样,我该怎么做?

With the Time module in python is it possible to measure elapsed time? If so, how do I do that?

我需要这样做,以便如果光标在小部件中停留了一定的时间,则会发生事件.

I need to do this so that if the cursor has been in a widget for a certain duration an event happens.

推荐答案

start_time = time.time()
# your code
elapsed_time = time.time() - start_time

您还可以编写简单的装饰器来简化各种功能的执行时间的测量:

You can also write simple decorator to simplify measurement of execution time of various functions:

import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()

        ret = fn(*args, **kwargs)

        elapsed_time = time.time() - start_time

        if fn.__name__ not in PROF_DATA:
            PROF_DATA[fn.__name__] = [0, []]
        PROF_DATA[fn.__name__][0] += 1
        PROF_DATA[fn.__name__][1].append(elapsed_time)

        return ret

    return with_profiling

def print_prof_data():
    for fname, data in PROF_DATA.items():
        max_time = max(data[1])
        avg_time = sum(data[1]) / len(data[1])
        print "Function %s called %d times. " % (fname, data[0]),
        print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
    global PROF_DATA
    PROF_DATA = {}

用法:

@profile
def your_function(...):
    ...

您可以同时配置多个功能.然后要打印测量值,只需调用print_prof_data():

You can profile more then one function simultaneously. Then to print measurements just call the print_prof_data():

这篇关于使用“时间"模块测量经过时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆