This code:
import random,time
raw_input()
while True:
try:
TIME += 0
except:
TIME = time.clock()
x = random.random()
if x > 0.999999:
print x
print time.clock()-TIME
break
Provided this output:
0.999999910337
63.5525445557
However, I tested on a stopwatch and I seemed to get a second and 3 quarters on the stopwatch. I wasn't going for an accurate reading, I was simply trying to figure out how many Windows wall clock seconds there are to every second.
2nd Try
0.999999028728
0.93168230208
Took a second and a quarter
I kept getting weird answers. Anyway, does anybody know? Or is it a rate?
Related
I want the alarm.play() function to repeat for the number of loops and ring 10 times as in the example, but it just keeps ringing once every time I try or change it. How can I fix this? And does it make more sense to use for instead of while ?
import time
import vlc
alarm = vlc.MediaPlayer("path")
m=0
while m<=10:
alarm.play()
time.sleep(1)
m +=1
just stop the alarm at the end of loop and befor stop it create loop for stop executing while the sound is playing
import time
import vlc
alarm = vlc.MediaPlayer("path")
m = 0
while m <= 10:
alarm.play()
time.sleep(1)
m += 1
while alarm.is_playing():
pass
alarm.stop()
I'm relatively new to Python so I don't know how difficult or easy this is to solve, but I'm trying to make a function that can measure time without blocking other code from executing while doing so. Here's what I have:
import time
def tick(secs):
start = time.time()
while True:
end = time.time()
elapsed = end - start
if elapsed >= secs:
return elapsed
break
input("what time is it?: ")
print(f"one: {round(tick(1))}")
print(f"two: {round(tick(2))}")
print(f"three: {round(tick(3))}")
print(f"four: {round(tick(4))}")
print(f"five: {round(tick(5))}")
The input blocks the timer from starting until it gets input, and the tick()'s after dont run simultaneously. Thus running one at a time like, wait 1 second then wait 2 seconds instead of wait 5 seconds (to be clear I want all timers that are started to run at the same time others are, so the 5 second timer would start at the same time the 1 second one does), thank you for your time and please let me know if you have a solution for this.
Not exactly sure what you are asking for, but how does this look:
import time
start=time.time()
input("what time is it?: ")
time.sleep(1)
print(time.time()-start)
time.sleep(2)
print(time.time()-start)
time.sleep(3)
print(time.time()-start)
time.sleep(4)
print(time.time()-start)
time.sleep(5)
print(time.time()-start)
The tick's are not running simultanously because your are first waiting for 1 second, then again you are waiting for 2, then again for 3, etc.
A simple thing to do is have a list of time intervals you want to "pause" at, in your case [1, 2, 3, 4, 5] which are sorted numerically. You will then keep track of the current index by checking elapsed >= secs and if it succedds you will increment it by one. Here's a glance
import time
def tick(tocks: list):
"""Tocks is a list of the time intervals which you want to be
notified at when are reached, all of them are going to run in parallel.
"""
tocks = sorted(tocks)
current = 0 # we are at index 0 which is the lowest interval
start = time.time()
while current < len(tocks): # while we have not reached the last interval
end = time.time()
elapsed = end - start
if elapsed >= tocks[current]: # if the current interval has passed check for the next
print(f"Tock: {tocks[current]}")
current += 1
This function can then be called like this
tick([1, 2, 3, 4, 5])
This will print 1 to 5 seconds at the same time. Here is the output
Tock: 1 # at 1 sec
Tock: 2 # at 2 sec
Tock: 3 # at 3 sec
Tock: 4 # .....
Tock: 5
You can imagine that this may have some minor flaws if you choose really close numbers like [0.5, 0.50001, 0.50002] and because the difference is so small 0.0001 seconds may not actually pass.
You could also try multithreading as has been noted, but it will be a very CPU-intensive (imagine wanting to count to 100 and you have to open 100 threads) task for something very simple.
Goal: I would like to see how many times python is able to print something per 1 second.
For educational purposes I'm trying to make a script that shows how many times per every second a random module will appear in a loop. How to do it in a fastest pythonic way?
At first, to count seconds I wrote this code:
import time
sec = 0
while True:
print(sec)
time.sleep(1)
sec += 1
But this one seems slower than a real seconds.
So I decided to use local seconds. Also, before continue my script I wanted to count how many times python will print 'you fool' manually, so I wrote following code:
import time
def LocalSeconds():
local_seconds = time.gmtime()[5:-3]
local_seconds = int(local_seconds[0])
return local_seconds
while True:
print(LocalSeconds(), 'you fool')
Output:
first second - 14 times per second;
next second - 13 times;
next second - 12 times, etc. Why it goes slower?
Where I end / stuck right now:
import time, random
def RandomNumbers():
return random.randint(3,100)
def LocalSeconds():
local_seconds = time.gmtime()[5:-3]
local_seconds = int(local_seconds[0])
return local_seconds
def LocalSecondsWithPing():
local_seconds_ping = time.gmtime()[5:-3]
local_seconds_ping = int(local_seconds[0:1])
return local_seconds_ping
record_seconds = []
record_seconds_with_ping = []
while True:
record_seconds.append(LocalSeconds())
record_seconds_with_ping.append(LocalSecondsWithPing())
if record_seconds == record_seconds_with_ping:
RandomNumbers()
del record_seconds_with_ping[0]
del record_seconds[-1]
Also, I guess I need to use "for" loop, not "while"? How to do this script?
Counting a single second won't give you a good result. The number of prints in a single second may vary depending on things like other threads currently running on your system (for the OS or other programs) and may be influenced by other unknown factor.
Consider the followind code:
import calendar
import time
NumOfSeconds=100 #Number of seconds we average over
msg='Display this message' #Message to be displayed
count=0 #Number of time message will end up being displayed
#Time since the epoch in seconds + time of seconds in which we count
EndTime=calendar.timegm(time.gmtime()) + NumOfSeconds
while calendar.timegm(time.gmtime())<EndTime: #While we are not at the end point yet
print(msg) #Print message
count=count+1 #Count message printed
print(float(count)/NumOfSeconds) #Average number of prints per second
Here calendar.timegm(time.gmtime()) gives us the time in seconds since the epoch (if you don't know what that is, read this. But basically it's just a fixed point in time most computer system now days use as a reference point.
So we set the EndTime to that point + the number of seconds we want to average over. Then, in a loop, we print the message we want to test and count the number of times we do that, between every iteration checking that we are not past the end time.
Finally we print the average number of times per seconds that we printed the message. This helps with the fact that we may end up start counting near the end of a whole second since the epoch, in which case we won't actually have a whole second to print messages, but just a fraction of that. If we make sure NumOfSeconds is large enough, that error addition will be small (for example, for NumOfSeconds=100 that error is ~1%).
We should note that the actual number would also depend on the fact that we are constantly testing the current time and counting the number of prints, however, while I haven't tested that here, it is usually the case that printing to the screen takes significantly longer time than those operations.
I am trying to make a basic wage timer for my brother who just got a job... What I wanted to have was a while loop running the code waiting for someone to press enter (or some other key) ends the loop and give the current wage. I was hoping to KeyboardInterrupt but if there is an easier way to do it I would love to hear about it. How could I do this?
a keyboard interrupt is generated only when someone hits ctrl-C or similar.
it sounds like your plan was to have code something like:
from time import sleep
wage = 0
try:
while True:
wage = wage + hourly_rate
sleep(60 * 60) # an hour in seconds
except KeyboardInterrupt:
print('you earned', wage)
and then have someone hit ctrl-C? which would work with a try/except. but if you want someone just to hit the return key then instead of adding things up, do some maths:
from time import time
start = time() # time in seconds from some arbitrary date in 1970 (it's a standard)
input('hit return to get your wage!')
end = time()
elapsed = end - start # time that has passed in seconds between start and end
wage = hourly_rate * elapsed / (60 * 60) # convert from hourly
print('you earned', wage)
the first version is a bit optimistic as it adds each hour at the start. the second is more accurate.
ps congrats to your brother!
I'm trying to write a python game loop that hopefully takes into account FPS. What is the correct way to call the loop? Some of the possibilities I've considered are below. I'm trying not to use a library like pygame.
1.
while True:
mainLoop()
2.
def mainLoop():
# run some game code
time.sleep(Interval)
mainLoop()
3.
def mainLoop():
# run some game code
threading.timer(Interval, mainLoop).start()
4.
Use sched.scheduler?
If I understood correctly you want to base your game logic on a time delta.
Try getting a time delta between every frame and then have your objects move with respect to that time delta.
import time
while True:
# dt is the time delta in seconds (float).
currentTime = time.time()
dt = currentTime - lastFrameTime
lastFrameTime = currentTime
game_logic(dt)
def game_logic(dt):
# Where speed might be a vector. E.g speed.x = 1 means
# you will move by 1 unit per second on x's direction.
plane.position += speed * dt;
If you also want to limit your frames per second, an easy way would be sleeping the appropriate amount of time after every update.
FPS = 60
while True:
sleepTime = 1./FPS - (currentTime - lastFrameTime)
if sleepTime > 0:
time.sleep(sleepTime)
Be aware thought that this will only work if your hardware is more than fast enough for your game. For more information about game loops check this.
PS) Sorry for the Javaish variable names... Just took a break from some Java coding.