如何在CherryPy中计时网页请求?

0 投票
2 回答
1066 浏览
提问于 2025-04-16 11:59

我想要测量一下,当我给CherryPy发送请求时,它返回一个页面需要多长时间。我该怎么做呢?

2 个回答

1

这要看你具体想要测量什么。如果你只是想测量页面处理的逻辑时间,可以使用Y. H. Wong发布的代码。如果你想测量用户看到的总时间,可以使用类似于Apache ab这样的工具:

$ python myproject.py &
$ ab -n 1000 -c 10 http://localhost:8080/myapp
1

你可以写一个装饰器:

import datetime
import cherrypy

def request_timer(f, *args, **kwargs):
    def _request_time(f, *args, **kwargs):
        begin = datetime.datetime.now()
        response = f(*args, **kwargs)
        end = datetime.datetime.now()
        print cherrypy.log('time took for request %s' % (end - begin))
        return response
    return _request_time(f, *args, **kwargs)

class Root(object):

    @request_timer
    def index(*args, **kwargs):
        pass
    index.exposed = True

这个日志信息会根据你的设置,显示在屏幕上或者写入你的错误日志文件中。

撰写回答