测量加载页面的时间 - Python

时间:2013-04-24 21:29:01

标签: python

我正在使用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

3 个答案:

答案 0 :(得分:3)

您需要使用网络浏览器吗?和你一样,你需要查看结果吗?

否则你可以这样做。

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

答案 1 :(得分:2)

使用装饰器的奇特方式

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

答案 2 :(得分:0)

如果您想在真实的浏览器中计时页面加载(包括页面加载的所有资源,渲染时间等),可以使用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()

如果要与加载时间等分开了解渲染时间,则可以加载许多other metrics