[英]measuring the time to load a page - 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
您需要使用网络浏览器吗? 至于你需要查看结果吗?
否则你可以这样做。
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
使用装饰器的奇特方式
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
如果您想在真实浏览器中为页面加载计时(包括它加载的所有资源、渲染时间等),您可以使用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()
如果您想与加载时间等分开了解渲染时间,则可以加载许多其他指标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.