Reputation: 21
I have been trying to calculate Python's execution time with this code, I've got the time but I don't know which number is being used from the list to be measured any help with how to print it would be helpful and much appreciated
import time
import random
def algorithm(c):
b = []
for i in c:
b.append(i*2)
def data():
c=[]
for x in range(10000000):
c.append(random.randint(1,100000))
timer(c)
def timer(c):
time_start = time.time()
algorithm(c)
time_end = time.time()
time_taken = time_end - time_start
print(time_taken)
data()
Upvotes: 2
Views: 43
Reputation: 51683
You could leverage the timeit
module:
import timeit
codeToExecute = """
def algorithm(c):
b = []
for i in c:
b.append(i*2)
algorithm(range(500))
"""
#
setupCode = "pass"
meas = timeit.timeit(stmt=codeToExecute, setup=setupCode, number=100000)
print(meas)
Output:
17.0021979809
This will execute the given function number times and print your time in seconds for it. You can use the setup to provide "data" or "imports" to your test that only has to be executed once and not on each run.
Upvotes: 1
Reputation: 21
import time
import random
import timeit
randomNumbersAndTime = {}
def algorithm(c):
b = []
for i in c:
b.append(i*2)
def data():
c=[]
setupCode = "pass"
print ("Random Number , Time Taken to Generate\n")
for x in range(10000000):
codeToExecute = str(random.randint(1,100000))
randomNumb = timeit.timeit(stmt=codeToExecute, setup=setupCode, number=1000000)
randomNumbersAndTime[codeToExecute] = randomNumb
for randomNumber in randomNumbersAndTime.keys() :
print ("{0} , {1} \n".format(randomNumber,randomNumbersAndTime[randomNumber]))
data()
Upvotes: 0
Reputation: 1445
I believe your code is fine you just need to restructure the code a bit.
import time
import random
import timeit
randomNumbersAndTime = {}
def algorithm(c):
b = []
for i in c:
b.append(i*2)
def data():
c=[]
setupCode = "pass"
print ("Random Number , Time Taken to Generate\n")
for x in range(10000000):
codeToExecute = str(random.randint(1,100000))
randomNumb = timeit.timeit(stmt=codeToExecute, setup=setupCode, number=1000000)
randomNumbersAndTime[codeToExecute] = randomNumb
for randomNumber in randomNumbersAndTime.keys() :
print ("{0} , {1} \n".format(randomNumber,randomNumbersAndTime[randomNumber]))
data()
this will give you the desired results.
This is a sample output :
Random Number , Time Taken to Generate
44806 , 0.433061423485
44806 , 0.433061423485
38079 , 0.44243301193
44806 , 0.433061423485
66713 , 0.435066187359
38079 , 0.44243301193
85426 , 0.422678350883
44806 , 0.433061423485
66713 , 0.435066187359
38079 , 0.44243301193
85426 , 0.422678350883
I hope i understood correctly .
Upvotes: 1