Measuring time since last time the if statement ran (Python) - python-3.x

I want to make my if statement run, only, if it is more than x seconds since it last ran. I just cant find the wey.

As you've provided no code, let's stay this is your program:
while True:
if doSomething:
print("Did it!")
We can ensure that the if statement will only run if it has been x seconds since it last ran by doing the following:
from time import time
doSomething = 1
x = 1
timeLastDidSomething = time()
while True:
if doSomething and time() - timeLastDidSomething > x:
print("Did it!")
timeLastDidSomething = time()
Hope this helps!

You'll want to use the time() method in the time module.
import time
...
old_time = time.time()
...
while (this is your game loop, presumably):
...
now = time.time()
if old_time + x <= now:
old_time = now
# only runs once every x seconds.
...

# Time in seconds
time_since_last_if = 30
time_if_ended = None
# Your loop
while your_condition:
# You still havent gone in the if, so we can only relate on our first declaration of time_since_last_if
if time_if_ended is not None:
time_since_last_if = time_if_ended - time.time()
if your_condition and time_since_last_if >= 30:
do_something()
# defining time_if_ended to keep track of the next time we'll have the if available
time_if_ended = time.time()

Related

Timer shutdown computer(python3.x)

i had code a timer shutdown pc which will shutdown after the times up, but it will keep printing the time remaining which is not good if i want to shutdown my computer after 30 minutes, it will print about 1800 lines, how should i modify it if i want it to print one line of time remaining which will keep changing.
import time
seconds = int(input("seconds:"))
for i in range(seconds):
x = (seconds - i)
print(x)
time.sleep(1)
check = input("do u want to shutdown ur computer?(yes/no):")
if check == "no":
exit()
else:
os.system("shutdown /s /t 1")
Try this. Just replace the string "Shutdown has started" with the shutdown command.
import time
import sys
x=int(input("seconds: "))
print("The timer has started. Time remaining for shut down: ")
def custom_print(string, how = "normal", dur = 0, inline = True):
if how == "typing": # if how is equal to typing then run this block of code
letter = 1
while letter <= len(string):
new_string = string[0:letter]
if inline: sys.stdout.write("\r")
sys.stdout.write("{0}".format(new_string))
if inline == False: sys.stdout.write("\n")
if inline: sys.stdout.flush()
letter += 1
time.sleep(float(dur))
if new_string=="0":
print("\nShut down has started")
else:
pass
for k in range(1,x+1):
k=x-k
custom_print(str(k), "typing", 1)

Parallel version of sorting algorithm faster / same as serial version?

I'm trying to implement multithreading and multiprocessing on a sorting algorithm. The way implemented it is by:
Initialize a list of 10k items
Assign a random variable between 0-100 for each element
arr = [1] * 10000
for x, i in enumerate(arr):
arr[x] = random.randint(0, 100)
t_arr = arr
m_arr = arr
s_arr = arr
Create 2 sub-lists -- one for values lower than or equal to 50 and one for the rest
I then used bubble sort for both sub-lists in parallel. One using threads and one using processes.
Theoretically both should be faster, but only multiprocessing is. Multithreading produces the same results.
I have already tried different sorting algos, problem is persistent.
# Threading Version
start_time = time.time()
subarr1 = []
subarr2 = []
# Split Array into 2
for i in t_arr:
if i <= 50:
subarr1.append(i)
else:
subarr2.append(i)
# Sort first array
t1 = threading.Thread(target=bubbleSort, args=(subarr1,))
# Sort second array
t2 = threading.Thread(target=bubbleSort, args=(subarr2,))
t1.start()
t2.start()
t1.join()
t2.join()
end_time = time.time() - start_time
print("--- %s seconds ---" % (end_time))
# Serial Version
start_time = time.time()
subarr1 = []
subarr2 = []
# Split Array into 2
for i in s_arr:
if i <= 50:
subarr1.append(i)
else:
subarr2.append(i)
# Sort first array
bubbleSort(subarr1)
# Sort second array
bubbleSort(subarr2)
end_time = time.time() - start_time
print("--- %s seconds ---" % (end_time))
# Multiprocessing Version
start_time = time.time()
subarr1 = []
subarr2 = []
# Split Array into 2
for i in s_arr:
if i <= 50:
subarr1.append(i)
else:
subarr2.append(i)
# Sort first array
p1 = multiprocessing.Process(target=bubbleSort, args=(subarr1,))
# Sort second array
p2 = multiprocessing.Process(target=bubbleSort, args=(subarr2,))
p1.start()
p2.start()
p1.join()
p2.join()
end_time = time.time() - start_time
print("--- %s seconds ---" % (end_time))
Multithreading: around 6 seconds
Serial: around 6 seconds (similar to Threading)
Multprocessing: around 3 seconds
These results are consistent. Any advice?

I have a code to make a motor run then sleep, then run again, but can't get it to work

I need to make a motor run for an amount of time, sleep for an amount of time, then repeat making an infinite loop
from adafruit_motorkit import MotorKit
import time
kit = MotorKit()
while True:
endtime = time.time() + 60 # runs motor for 60 seconds
while time.time() < endtime:
kit.motor1.throttle = 1
pass
print('endtime passed')
time.sleep(10)
print('done sleeping')
I'm expecting the motor to run for a minute, give the endtime passed message, and sleep for 10 seconds, but the motor never sleeps. I'm new to python so I don't know much about this and any help is appreciated.
You need to set the throttle back to 0 before calling time.sleep.
time.sleep will only pause the process for the given time, you need to explicitly tell the motor to stop moving.
Example:
while True:
endtime = time.time() + 60 # runs motor for 60 seconds
while time.time() < endtime:
kit.motor1.throttle = 1
pass
print('endtime passed')
kit.motor1.throttle = 0
time.sleep(10)
print('done sleeping')
Also you don't have to busy-wait the 60 seconds the motor is running, you can just set the throttle on the motor and then call time.sleep:
from adafruit_motorkit import MotorKit
import time
kit = MotorKit()
while True:
print('running motor')
kit.motor1.throttle = 1
time.sleep(60)
print('pausing 10 seconds')
kit.motor1.throttle = 0
time.sleep(10)
print('done sleeping')

python3 time result not correct

I got the follow code. I have added time() to it to let me calculate the delay between when the user get's the problem and when the user inputs the data.
But the resulting time is not always correct and I am not sure why.
from time import time
from random import randint
a = randint(0,1000)
b = randint(0,1000)
cor_answer = a+b
usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))
start = time()
if usr_answer == cor_answer:
print("yes you are correct!")
else:
print("no you are wrong!")
end = time()
elapsed = end - start
print("That took you "+str(elapsed)+" seconds. \n")
This is the result executing from cmdline:
~/math_quiz/math_quiz$ python3 math_quiz.py
what is 666+618?
1284
1284
1284
yes you are correct!
That took you 4.291534423828125e-05 seconds.
But time() clearly works because if I run it in IDLE I get this:
>>> start = time()
>>> time()-start
13.856008052825928
So I am not sure why the execution from cmdline gets me a different result.
Thanks
Your code currently start the timer after user input the answer
You need to put this code start = time() before usr_answer = int(input("what is "+str(a)+"+"+str(b)+"? \n"))

Stopwatch program

I need to make a stop watch program, I need Start, Stop, Lap, Reset and Quit functions. The program needs print elapsed times whenever the Stop or Lap key is pressed. When the user chooses to quit the program should write a log file containing all the timing data (event and time) acquired during the session in human readable format.
import os
import time
log = ' '
def cls():
os.system('cls')
def logFile(text):
logtime = time.asctime( time.localtime(time.time()) )
f = open('log.txt','w')
f.write('Local current time :', logtime, '\n')
f.write(text, '\n\n')
f.close()
def stopWatch():
import time
p = 50
a = 0
hours = 0
while a < 1:
cls()
for minutes in range(0, 60):
cls()
for seconds in range(0, 60):
time.sleep(1)
cls()
p +=1
print ('Your time is: ', hours, ":" , minutes, ":" , seconds)
print (' H M S')
if p == 50:
break
hours += 1
stopWatch()
I have it ticking the time, however they way I have it wont allow me to stop or lap or take any input. I worked to a few hours to find a way to do it but no luck. Any Ideas on how im going to get the functions working?

Resources