webpy 性能调优记录页面执行时间,webpy调优,记录网站执行时间是一个很


记录网站执行时间是一个很通用的功能,在需要调优时经常会用得到,你可以看到OutOfMemory.CN的每个页面的页脚都有_耗时xx秒_的信息。

实现方法是通过webpy的add_processor给页面执行加上钩子,首先在run.py 文件中添加如下python代码:

def timespent_processor(handler):    web.ctx.starttime = time.time()    result = handler()    return resultapp.add_processor(timespent_processor)

代码中的app是初始化的application,这里将页面开始执行的时间放到了web.ctx对象中。我们需要在页面输出完成后记录结束时间,然后计算总执行时间,结束时间代码需要加到webpy模板页的底部。

如下是我的实现代码:

$if web.ctx.get('starttime',None):        $ timespent = time.time()-web.ctx.starttime        <span class="timespent"><i>耗时${'%05.3f'%(timespent,)}s</i></span>

这里首先判断是否设置了starttime,如果设置了,就用当前时间减去开始时间,并输出到页面上。

评论关闭