Skip to content

Instantly share code, notes, and snippets.

@falcondai
Created May 2, 2012 17:58
Show Gist options
  • Save falcondai/2578731 to your computer and use it in GitHub Desktop.
Save falcondai/2578731 to your computer and use it in GitHub Desktop.
This computes the average run time of a piece of python code.
# File: benchmark.py
# Desc: This computes the average run time of a piece of code.
# Author: Falcon Dai
# Date: 5/2/2012
import time
global_dict = globals()
# should be run as soon as the module is imported to
def set_global_dict(dict):
global global_dict
global_dict = dict
def update_global_dict(dict):
global_dict.update(dict)
def perform_time(code, count=1000, gd=None):
"""
execute a piece of code for some times and return the average execution time.
@param: code - the code to be execute and time
count - the number of times to execute the code (defult: 1000)
gd - the global identifier dictionary in the execution
@return: the average time of execution of the code in seconds
"""
if gd == None:
gd = global_dict
start_time = time.clock()
for i in range(count):
eval(code, gd)
return (time.clock() - start_time) / count
if __name__=='__main__':
for i in range(10):
print perform_time('1+1', 10**i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment