1#!/usr/bin/env python 2 3# Copyright 2011 Google Inc. All Rights Reserved. 4# 5# Licensed under the Apache License, Version 2.0 (the "License"); 6# you may not use this file except in compliance with the License. 7# You may obtain a copy of the License at 8# 9# http://www.apache.org/licenses/LICENSE-2.0 10# 11# Unless required by applicable law or agreed to in writing, software 12# distributed under the License is distributed on an "AS IS" BASIS, 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14# See the License for the specific language governing permissions and 15# limitations under the License. 16 17"""measure the runtime of a command by repeatedly running it. 18""" 19 20from __future__ import print_function 21 22import time 23import subprocess 24import sys 25 26devnull = open('/dev/null', 'w') 27 28def run(cmd, repeat=10): 29 print('sampling:', end=' ') 30 sys.stdout.flush() 31 32 samples = [] 33 for _ in range(repeat): 34 start = time.time() 35 subprocess.call(cmd, stdout=devnull, stderr=devnull) 36 end = time.time() 37 dt = (end - start) * 1000 38 print('%dms' % int(dt), end=' ') 39 sys.stdout.flush() 40 samples.append(dt) 41 print() 42 43 # We're interested in the 'pure' runtime of the code, which is 44 # conceptually the smallest time we'd see if we ran it enough times 45 # such that it got the perfect time slices / disk cache hits. 46 best = min(samples) 47 # Also print how varied the outputs were in an attempt to make it 48 # more obvious if something has gone terribly wrong. 49 err = sum(s - best for s in samples) / float(len(samples)) 50 print('estimate: %dms (mean err %.1fms)' % (best, err)) 51 52if __name__ == '__main__': 53 if len(sys.argv) < 2: 54 print('usage: measure.py command args...') 55 sys.exit(1) 56 run(cmd=sys.argv[1:]) 57