Get execution time of code x amount of times - python

What I am trying to do is run this program, get the execution time of it, and then continue to do that 9 more times. How would I go about iterating over it to get it to print out 10 different execution times? I'm not quite sure how I need to structure the program in order to accomplish this.
import time
start_time = time.time()
def fibonacci():
previous_num, result = 0, 1
user = 1000
iteration = 10
while len(str(result)) < user:
previous_num, result = result, previous_num + result
while iteration != 0:
iteration -= 1
end = time.time()
print(start_time - end)
return result
print(fibonacci())
print("--- %s seconds ---" % (time.time() - start_time))

All you need to do is create a for loop and put your code in it.
import time
def fibonacci(start_time):
previous_num, result = 0, 1
user = 1000
iteration = 10
while len(str(result)) < user:
previous_num, result = result, previous_num + result
while iteration != 0:
iteration -= 1
end = time.time()
print(start_time - end)
return result
for i in range(0, 10):
start_time = time.time()
print(fibonacci(start_time))
print("--- %s seconds ---" % (time.time() - start_time))

Related

Why does using sleep(1) is not the same thing as 1 - (time() - initTime

I am studying a code and i want to understand why using this:
initTime = time()
sleep(1 - (time() - initTime))
instead of:
sleep(1)
The purpose is just to count down the time out until 30, so...
Is not the same thing?
from time import time, sleep
def __wait_for_element__(self, element_tag, locator, timeout=30):
"""Wait till element present. Max 30 seconds"""
result = False
self.driver.implicitly_wait(0)
locator = locator.upper()
for i in range(timeout):
initTime = time()
try:
if locator == 'ID' and self.is_element_present(By.ID, element_tag):
result = True
break
elif locator == 'NAME' and self.is_element_present(By.NAME, element_tag):
result = True
break
elif locator == 'XPATH' and self.is_element_present(By.XPATH, element_tag):
result = True
break
elif locator == 'CSS' and self.is_element_present(By.CSS_SELECTORS, element_tag):
result = True
break
else:
logging.info(f"Error: Incorrect locator = {locator}")
except Exception as e:
logging.error(e)
print(f"Exception when __wait_for_element__ : {e}")
sleep(1 - (time() - initTime))
else:
print(
f"Timed out. Element not found with {locator} : {element_tag}")
self.driver.implicitly_wait(DEFAULT_IMPLICIT_WAIT)
return result
time() - initTime is the time of reading each repetition of the loop.
For a single repetition of the loop, it takes time() - initTime for reading + 1 - (time() - initTime) of sleep.
At total: 1 - (time() - initTime) + (time() - initTime) = 1 second.
Therefore, when using sleep(1 - (time() - initTime)), each loop repetition time is very close to 1 second.
Why not using sleep(1)? -Because it is not as precised. Each loop iteration will last for more than 1 second: (time() - initTime) of reading it + 1 second of sleep.

Check a condition every 3 minutes without functions and without interrupting the loop

I have this working code that checks a conditions every 3 minutes considering the local time, so every 0, 3, 6, 9.....It prints "checking condition".
import time
def get_next_time():
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
return result
next_run = get_next_time()
while True:
now = time.localtime()
if next_run == now.tm_min:
print("checking condition")
#some condition
next_run = get_next_time()
time.sleep(1)
The problem is that I need the code without functions, so I need to find a way to write this code without using any funcion, and I cannot use break or interrput the loop
I tried:
while True:
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
now = time.localtime()
if result == now.tm_min:
print("checking conditions")
time.sleep(1)
But it does not work: it does not do nothing.
Any ideas?
you can compact the function in one statement:
import time
next_run = (3 - (time.localtime().tm_min % 3) + time.localtime().tm_min)%60
while True:
now = time.localtime()
if next_run == now.tm_min:
print("checking condition")
#checking conditions...
next_run=(3 - (time.localtime().tm_min % 3) + time.localtime().tm_min)%60
time.sleep(1)
The first time, the get_next_time() will only be executed when next_run == now.tm_min. The second time, you execute it each loop
import time
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
while True:
now = time.localtime()
if result == now.tm_min:
print("checking conditions")
minute = time.localtime().tm_min
result = 3 - (minute % 3) + minute
if result == 60:
result = 0
time.sleep(1)
Rounding to the next multiple of 3 minutes contradicts the specification "every 0...".
It is enough to do
import time
first= True
while True:
minute= time.localtime().tm_min
if first or minute == target:
print("checking condition")
first= False
target= (minute + 3) % 60
time.sleep(1)
Update:
I modified the code so that a single call to localtime is made on every iteration, to make fully sure that the minutes do not change between the calls.
More compact but less efficient:
import time
while True:
minute= time.localtime().tm_min
if 'target' not in locals() or minute == target:
print("checking condition")
target= (minute + 3) % 60
time.sleep(1)

for-loop with a timeout inside the loop?

I'm trying to find a way to do a for loop, and if the iteration of the for loop is more than the timeout, then it break and go to the next iteration.
Example :
timeout = 60
for i in mylist:
i += 1
if time > timeout:
break
I think you can use the time module as shown here:
import time
#get the time at the start of the program
x = time.localtime(time.time())
start_time = time.strftime('%S', x)
#the loop
timeout = 5
for i in range(10000000):
i += 1
y = time.localtime(time.time())
now_time = time.strftime('%S', y)
run_time = int(now_time) - int(start_time)
print(run_time) #to see the run_time
if run_time > timeout:
break
Assuming that a single iteration doesn't take so much, just use time module and a while loop as follows:
mylist = [1,2,3]
import time
timeout = 60
time_start = time.time()
i = 0
while i < len(mylist) and time.time() - time_start < timeout:
# do your stuff
i += 1
if i == len(mylist):
# this code runs if the iteration has completed, pass does nothing
pass
else:
# and this code runs if there was a timeout
pass

What is the time difference between a normal python code and the same code in multiprocessing?

I'm trying to clearly understand the difference of a function in single process and the same function in multiple cores. The following normal python code and multiprocessor code gives the same time (approx). Am i using multiprocessing wrong?
Normal Python code:
import time
def basic_func(x):
if x == 0:
return 'zero'
elif x % 2 == 0:
return 'even'
else:
return 'odd'
def multiprocessing_func(x):
y = x * x
print('{} squared results in a/an {} number'.format(x, basic_func(y)))
if __name__ == '__main__':
starttime = time.time()
for each in range(0, 1000):
multiprocessing_func(each)
print('That took {} seconds'.format(time.time() - starttime))
Multiprocessing code:
import time
import multiprocessing
def basic_func(x):
if x == 0:
return 'zero'
elif x % 2 == 0:
return 'even'
else:
return 'odd'
def multiprocessing_func(x):
y = x * x
print('{} squared results in a/an {} number'.format(x, basic_func(y)))
if __name__ == '__main__':
starttime = time.time()
pool = multiprocessing.Pool()
pool.map(multiprocessing_func, range(0, 1000))
pool.close()
print('That took {} seconds'.format(time.time() - starttime))
Thanks in advance !
code source : This tutorial
Without multiprocessing, I executed this code in 0.07s. The multiprocessing version took 0.28s. Create some pool of processes take some times and it may not be worth it.
I recommend not printing during the process as it could create a funnel effect (I/O is always an issue for concurrent processes)
Changing a little bit your code :
import time
import multiprocessing
def basic_func(x):
if x == 0:
return 'zero'
elif x % 2 == 0:
return 'even'
else:
return 'odd'
def multiprocessing_func(x):
y = x * x
return basic_func(y)
And comparing results :
starttime = time.time()
for each in range(0, 100000000):
multiprocessing_func(each)
print('That took {} seconds'.format(time.time() - starttime))
Took 34s
starttime = time.time()
pool = multiprocessing.Pool(processes=10)
pool.map(multiprocessing_func, range(0, 100000000))
pool.close()
print('That took {} seconds'.format(time.time() - starttime))
Took 9.6s
See that the "same" problem had drastic different results. Answering your question is not possible, it depends too much on the initial problem, funnel effects and the balance between the duration of the task and the cost of creating pool of processes.

Python 3: Nested while loops based time

I am trying to run two while loops based on an input condition. In this example, that is taken out and replaced by a 1 == 0 so that 0 can be changed back and forth for testing. Once selected, each while loop should run for 10 seconds and then the input condition checked (replaced by 1 == 0) again.
The problem appears to be in the time comparison, since it never evaluates correctly. What am I missing?
#!/usr/bin/env python3
import time
import os
import bellmod
while True:
starttime = time.time()
print("Start time " + str(starttime)) #Time check
elapsedtime = 0 #Reset elasped time to 0 for each loop iteration.
if 1 == 0: #Change this to run either loop. See if remote or local has precidence.
while(elapsedtime < 10):
print("Inside remote while " + time.strftime("%H:%M:%S")) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
else:
elapsedtime = 0
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
Your inner while loops are endless, because elapsedtime is never updated:
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
elapsedtime is updated after the while loop ends, but that is never reached.
You need to fix your indentation so elapsedtime is calculated each loop iteration:
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
Note that while is not a function. Using (...) groups the test expression, but is not needed or normally used. If you pass in values as separate arguments to print(), that takes care of including a separator and conversion to string for you:
while elapsedtime < 10:
print("inside bottom of local while", int(time.time() - starttime))
elapsedtime = time.time() - starttime
If you don't need to use elapsedtime in the loop, just inline the calculation:
while time.time() - starttime < 10:
print("inside bottom of local while", int(time.time() - starttime))
You don't change elapsedtime inside the loop ... it's stuck at 0.
Indent the last line:
if 1 == 0: #Change this to run either loop. See if remote or local has precidence.
while(elapsedtime < 10):
print("Inside remote while " + time.strftime("%H:%M:%S")) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.
else:
elapsedtime = 0
while(elapsedtime < 10):
print("inside bottom of local while " + str(int(time.time() - starttime))) #Time check
elapsedtime = time.time() - starttime #Calculate elasped time.

Categories

Resources