How could I knwow the execution time of a code in Python in microseconds? I have tried time.time and timeit.timeit but I can't have a good output
Try this,
import time
def main():
print [i for i in range(0,100)]
start_time = time.clock()
main()
print time.clock() - start_time, "seconds"
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0.00255163020819 seconds
Update
Don't forget to import time
Place this line start_time = time.clock()
before your code and place this
print time.clock() - start_time, "seconds"
at the end of code.
Update
# Top Of script file.
def main():
print [i for i in range(0,100)]
start_time = time.clock()
#YOUR CODE HERE - 1
main()
#YOUR CODE HERE - N
print time.clock() - start_time, "seconds"
You can also write decorator for measuring time,
import time
def dec(func):
def wrapper(*args, **kwargs):
start = time.time()
func(*args, **kwargs)
end = time.time()
print(end - start)
return wrapper
@dec
def test():
for i in range(10):
pass
test()
# output shows here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With