[英]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.