1

我正在使用webbrowser,所以我可以打开一个 html 来进行我目前正在进行的性能测试。这一小段代码是自动化的开始。该函数的目标perf_measure是返回url完全加载页面所用的时间。

import webbrowser

def perf_measure(url=""):

    try:
        webbrowser.open(url)

    except webbrowser.Error, e:
        print "It couldn't open the url: ", url

url = "www.google.com"
open_browser(url)

我怎样才能做到这一点?我只需要以秒为单位的值,例如:

www.google.com  Total time to load page in (secs): 2.641
4

3 回答 3

7

您需要使用网络浏览器吗?如您需要查看结果吗?

否则你可以这样做。

import urllib2
from time import time

stream = urllib2.urlopen('http://www.rarlab.com/rar/winrar-x64-420.exe')
start_time = time()
output = stream.read()
end_time = time()
stream.close()
print(end_time-start_time)

如果您想要更易于阅读的结果,可以使用round

print(round(end_time-start_time, 3))

输出

0.865000009537 # Without Round
0.865          # With Round
于 2013-04-24T21:31:32.270 回答
3

一种使用装饰器的奇特方式

import time

def time_it(func):
    def wrapper(*arg,**kw):
        t1 = time.time()
        res = func(*arg,**kw)
        t2 = time.time()
        return (t2-t1),res,func.func_name
    return wrapper

@time_it
def perf_measure(url=""):
    #w hatever you want
    pass
于 2013-04-24T21:33:16.767 回答
3

如果您想在真实浏览器中计时页面加载(包括它加载的所有资源、渲染时间等),您可以使用Selenium Webdriver。这将打开您选择的浏览器,加载 URL,然后提取时间:

from selenium import webdriver


def time_url(driver, url):
    driver.get(url)

    # Use the browser Navigation Timing API to get some numbers:
    # https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
    navigation_start = driver.execute_script(
        "return window.performance.timing.navigationStart")
    dom_complete = driver.execute_script(
        "return window.performance.timing.domComplete")
    total_time = dom_complete - navigation_start

    print(f"Time {total_time}ms")


driver = webdriver.Chrome()

try:
    url = "https://httpbin.org/delay/"
    time_url(driver, url + '1')
    time_url(driver, url + '2')

finally:
    driver.close()

如果您想将渲染时间与加载时间等分开,您可以加载许多其他指标。

于 2020-07-31T17:47:17.230 回答