10 examples of 'how to time a function in python' in Python

Every line of 'how to time a function in python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
21def funcer(*args, **kwargs):
22 start_time = time.time()
23 result = func(*args, **kwargs)
24 end_time = time.time()
25 print("{}:{}".format(func.__name__, end_time - start_time))
26 return result
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

58def time_this(original_function):
59 print "decorating"
60 def new_function(*args,**kwargs):
61 print "starting decoration"
62 x = original_function(*args,**kwargs)
63 return x
64 return new_function
190def _wrapper(*args,**kwargs):
191 start_time = time.time()
192 func(*args, **kwargs)
193 print('func_name: {}, spent time: {}s'.format(func.__name__, time.time() - start_time))
237def time_this_method(f):
238 """
239 Rather primitive way of timing a method. More advanced would be the profilehooks module.
240 """
241 from functools import wraps
242
243 @wraps(f)
244 def wrapper(*args, **kwargs):
245 t1 = time.perf_counter()
246 result = f(*args, **kwargs)
247 t2 = time.perf_counter()
248 diff = t2 - t1
249 if diff > 0.5:
250 print('Time for "{}()": {:5.3f} s'.format(f.__name__, diff))
251 else:
252 print('Time for "{}()": {:5.3f} ms'.format(f.__name__, diff * 1000))
253 return result
254
255 return wrapper
17def time_func(tag, func):
18 t0 = time.time() if tag else None
19 ret = func()
20 if tag:
21 t1 = time.time()
22 print('Time for {}: {}'.format(tag, t1 - t0))
23 return ret
76def timeit(func, *args, **kwargs):
77 t0 = datetime.now()
78 result = func(*args, **kwargs)
79 t1 = datetime.now()
80 diff = t1 - t0
81 return {'secs': diff.total_seconds(), 'return_value': result}
40@wraps(fn)
41def time_fn(*args, **kwargs):
42 start = time.time()
43 output = fn(*args, **kwargs)
44 end = time.time()
45 logger.debug(f'Timed: {fn.__name__} {round((end - start) * 1000, 4)}ms')
46 return output
59def time_it(fn, *args):
60 """
61 Timing function
62 """
63 start = time.time()
64 ret = fn(*args)
65 end = time.time()
66 return ((end - start) * 1000, ret)
15def timef(n, use_cython):
16 pyorcy.USE_CYTHON = use_cython
17 t1 = time()
18 v = f(n, n)
19 delta = time() - t1
20 print("n = %d f = %.1f use_cython = %s time: %.3fs"
21 % (n, v, use_cython, delta))
22 return delta
30def time_func(stmt, n=10, setup='from __main__ import *'):
31 t = timeit.Timer(stmt, setup)
32 total_time = t.timeit(n)
33 iter_time = total_time / n
34 iter_per_sec = n / total_time
35 print "func:%s nIter:%s total_time:%s iter_time:%s iter_per_sec: %s" % (stmt, n, total_time, iter_time, iter_per_sec)

Related snippets