When the time expires, the function starts again from the beginning - python

import pygame as pg
pg.init()
def fixTime():
totalTime = 4
return totalTime
while 1:
flowTime = int(pg.time.get_ticks()/1000)
elapsed_time = (fixTime() - flowTime)
if elapsed_time <=0:
fixTime()
else:
print(elapsed_time)
When the current ends, 1 is repeated, but I want to make a function that returns the time to the beginning.

Just use pygame.time.get_ticks():
Return the number of milliseconds since pygame.init() was called.
You can just subtract 2 time values:
def get_elapsed_time(from_time = 0):
to_time = pygame.time.get_ticks()
return to_time - from_time
start_time = pygame.time.get_ticks():
while run:
elapsed = get_elapsed_time(start_time)
# [...]
pygame.time.get_ticks() returns the time in milliseconds. If you want the time in seconds you must divide by 1000. e.g.: return (to_time - from_time) / 1000

Related

TypeError: '>=' not supported between instances of 'str' and 'tuple'

It works if I type if int(hour) >= 19: but I would like it to work with something similar to this line if current_time >= exit_time:
import time
current_time = time.strftime('%H:%M:%S')
exit_time = ('19:00:00','%H:%M:%S')
hour = time.strftime('%H')
minute = time.strftime('%M')
second = time.strftime('%S')
if current_time >= exit_time:
print ("It's time to go home")
else:
print ("{} hours, {} minutes and {} seconds to go home".format(18-int(hour),
59-int(minute), 59-int(second)))
Notice that you're comparing current_time (which is a string) and exit_time (which is a tuple containing 2 strings).
Maybe try something like:
if current_time >= exit_time[0]:
# your code
Since the first member of the tuple is probably what you want to compare to current_time.
Hope this helps!
The best alternative to this is.
from datetime import datetime
current_time = datetime.now().replace(microsecond=00)
exit_time = current_time.replace(hour=19, minute=00, second=00, microsecond=00)
if current_time >= exit_time:
print ("It's time to go home")
else:
time_delta = (exit_time - current_time).total_seconds()
hours_left = int(time_delta // 60 // 60)
minutes_left = int(time_delta // 60) - hours_left*60
seconds_left = int(time_delta) - hours_left*3600 - minutes_left*60
print ("{} hours, {} minutes and {} seconds to go home".format(hours_left,
minutes_left, seconds_left))

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

Get execution time of code x amount of times

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))

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.

Timer in Pygame

I'm completely new to Python and I'm trying to set a timer in this game I have... Everything else has been fine but this timer is a headache.
I'll only post the parts associated with the timer to make it easier.
frame_count = 0
second = 0
minute = 5
hour = 1
time = "1 5. 0"
And then in my main loop I have.
font = pygame.font.SysFont('DS-Digital', 50, False, False)
text = font.render(time,True,red)
display.blit(text, [302, 50])
frame_count += 1
if frame_count == 60:
frame_count = 0
second -= 1
elif second == 0:
second = 9
minute -= 1
elif minute == 0:
minute = 9
hour -= 1
elif second == 0 and minute == 0 and hour == 0:
second = 0
minute = 0
hour = 0
hour = time[0]
minute = time[2]
second = time[5]
clock.tick(60)
This gives me back an error for being wrong type but I've tried converting to int and vice versa... So frustrating...
I've looked at so many examples but most examples are actual minutes and seconds.
I need my right number to just countdown from 9 to 0 then minus off middle number and so forth.
If this your whole code then you didn't imported pygame. (import pygame) at the begining and you should loop it all so for example:
import pygame
while True:
...
Your code
...
Specify more your question please, I see that you should use if insted of elif because once it got to 1 1 0 it will turn to 1 0 9 and then into 0 9 9 in two frames.
elif second == 0 and minute == 0 and hour == 0:
second = 0
minute = 0
hour = 0
This doesn't make sence really it's like if you calculate
if I have a = 0 then do a = 0 if you know what I mean (it does nothing).
Edit:
There is working code, you can edit it and replace your old code with it.
import pygame
pygame.init()
screen = pygame.display.set_mode((500, 500))
red = (255, 0, 0)
bg_color = (0, 0, 0)
frame_count = 0
time = "1 5. 0"
while True:
pygame.time.Clock().tick(60)
frame_count += 1
hour = int(time[0])
minute = int(time[2])
second = int(time[5])
if second > 0 and frame_count == 20:
frame_count = 0
second -= 1
if second == 0 and minute > 0 and frame_count == 20:
frame_count = 0
second = 9
minute -= 1
if minute == 0 and hour > 0 and frame_count == 20:
frame_count = 0
minute = 9
second = 9
hour -= 1
time = str(hour) + " " + str(minute) + ". " + str(second)
font = pygame.font.SysFont('DS-Digital', 50, False, False)
text = font.render(time, True, red)
screen.fill(bg_color)
screen.blit(text, (302, 50))
pygame.display.update()
I'm quite sure that there is easier solution or more pythonic one, but it works and that is most important.
Remove these lines:
hour = time[0]
minute = time[2]
second = time[5]
it should work without them. Then ask what you are attempting to do with them
When you assign elements from time to you hour, minute, second variables convert them to an int like this:
hour = int(time[0])
minute = int(time[2]
second = int(time[5])
Here is my solution for simple way to sleep at the end of each iteration for the leftover time for a desired update rate
from timeit import default_timer as timer
from time import sleep as sleep
class loop_timer():
""" simple game loop timer that sleeps for leftover time (if any) at end of each iteration"""
LOG_INTERVAL_SEC=10
def __init__(self, rate_hz:float):
''' :param rate_hz: the target loop rate'''
self.rate_hz=rate_hz
self.start_loop()
self.loop_counter=0
self.last_log_time=0
def start_loop(self):
""" can be called to initialize the timer"""
self.last_iteration_start_time=timer()
def sleep_leftover_time(self):
""" call at start or end of each iteration """
now=timer()
max_sleep=1./self.rate_hz
leftover_time=max_sleep-(now-self.last_iteration_start_time)
if leftover_time>0:
sleep(leftover_time)
self.start_loop()
self.loop_counter+=1
if now-self.last_log_time>self.LOG_INTERVAL_SEC:
self.last_log_time=now
if leftover_time>0:
print('loop_timer slept for {:.1f}ms leftover time for desired loop interval {:.1f}ms'.format(leftover_time*1000,max_sleep*1000))
else:
print('loop_timer cannot achieve desired rate {}Hz, time ran over by {}ms compared with allowed time {}ms'.format(self.rate_hz, -leftover_time*1000, max_sleep*1000))
Use it like this
looper=loop_timer(MODEL_UPDATE_RATE_HZ)
while not self.exit:
# do your stuff here
try:
looper.sleep_leftover_time()
except KeyboardInterrupt:
logger.info('KeyboardInterrupt, stopping')
self.exit=True
continue

Categories

Resources