Skip to content

Instantly share code, notes, and snippets.

@akaihola
Created April 5, 2012 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akaihola/2309083 to your computer and use it in GitHub Desktop.
Save akaihola/2309083 to your computer and use it in GitHub Desktop.
Warms up a web server by sending requests until the maximum or average response duration falls below a given threshold
#!/usr/bin/env python3
# also compatible with Python 2.7
# and Python 2.6 (requires argparse)
"""
Warms up a web server by sending requests until the maximum or average response
duration falls below a given threshold.
"""
# See warmup.py -h for usage.
try:
from argparse import ArgumentParser
except ImportError:
import sys
sys.exit('Please "pip install argparse" if you\'re on Python <2.7')
from collections import deque
import time
try:
from urllib2 import urlopen # Python 2.x
except ImportError:
from urllib.request import urlopen # Python 3.x
try:
range = xrange # Python 2.x
except NameError:
pass # Python 3.x
def main(options):
window = deque()
window_time = 0.0
print('reqno duration average maximum window')
request_no = 0
while not options.num_requests or request_no < options.num_requests:
request_no += 1
start = time.time()
response = urlopen(options.url[0])
response.read()
end = time.time()
elapsed_ms = 1000 * (end - start)
window.append(elapsed_ms)
window_time += elapsed_ms
if len(window) > options.window_size:
window_time -= window.popleft()
window_size = len(window)
average = window_time / window_size
longest = max(window)
print('{request_no:5}'
' {elapsed_ms:6.0f}ms'
' {average:5.0f}ms'
' {longest:5.0f}ms'
' {window_size:6}'.format(**locals()))
if window_size == options.window_size:
if options.max_cutoff and longest <= options.max_cutoff:
break
if options.avg_cutoff and average <= options.avg_cutoff:
break
if __name__ == '__main__':
p = ArgumentParser(description=__doc__)
p.add_argument('url', nargs=1,
help='The URL to test')
p.add_argument('-n', '--num-requests', type=int, default=100,
help='Maximum number or requests. 0=forever, default=100.')
p.add_argument('-w', '--window-size', type=int, default=10,
help='Window size to look at, default=10',
metavar='WINSIZE')
p.add_argument('-m', '--max-cutoff', type=int, default=0,
help=('Stop when all last WINSIZE responses are faster than'
" this, 0=don't stop (the default)"))
p.add_argument('-a', '--avg-cutoff', type=int, default=0,
help=('Stop when average duration of last WINSIZE requests'
" is less than this, 0=don't stop (the default)"))
opts = p.parse_args()
main(opts)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment