How to perform an operation at a specified rate [duplicate] - python

This question already has answers here:
How to repeatedly execute a function every x seconds?
(22 answers)
How to make a proper server tick?
(1 answer)
Closed 5 years ago.
I have a function that I want to call, say, 10 times per second. I start out with code like this:
while True:
the_operation()
time.sleep(1.0/TIMES_PER_SECOND)
This works ok but the_operation is called slightly less often than desired, because the time to do the operation itself. We can make the code look like this instead:
while True:
t = time.time()
the_operation()
time_to_sleep = 1.0/TIMES_PER_SECOND - (time.time() - t)
if time_to_sleep > 0:
time.sleep(time_to_sleep)
This is better, but still not good enough -- the time to execute the loop is not considered, and if the_operation happens to take significantly longer than 1/TIMES_PER_SECOND in one iteration, our throughput will be too low. The operation on average takes less than 1/TIMES_PER_SECOND, but the code needs to handle the cases where it does take longer.
What is a good pattern for calling the_operation at the specified rate?

Related

How would I be able to have certain lines of code be executed randomly? [duplicate]

This question already has answers here:
Percentage chance to make action
(4 answers)
Closed 10 months ago.
I feel this should be an obvious answer, however, I am having issues coding a personal project of mine. How would I be able to have certain lines of code be executed randomly?
Not from the project itself but the principles are still, say for example I would want the following code to be executed every 1/1000 times or so.
print("Lucky!")
How would I exactly be able to do that?
Set a trace function that will have a 1/1000 chance to print:
import random, sys
def trace(frame, event, arg):
if random.random() < 1/1000:
print("Lucky!")
return trace
sys.settrace(trace)
You're welcome to test it with a 1/2 chance.
Generate a random integer in the range [0,1000). Pick any single value in the range, and check for equality to see if you should print.
import random
def lucky():
if random.randrange(1000) == 42:
print("Lucky!")

Can anyone please explain how does inputimeout() in python work? [duplicate]

This question already has answers here:
Skip the input function with timeout
(2 answers)
Closed 1 year ago.
I want to take a timed input. If the user doesn't give the input under a limited amount of seconds, the program moves on. So, I learned about inputimeout() but even when I am giving the input within the time limit, it just waits for the timeout. (Also I am not able to solve the problem from other similar questions and that is why I decided to mention this problem)
from inputimeout import inputimeout, TimeoutOccurred
try:
something = inputimeout(prompt = 'Enter: ', timeout=5)
except TimeoutOccurred:
print('Time Over')
Output for the above code:
Enter: e
Time Over
Process finished with exit code 0
Even if I give the input within the time limit, it shows Time Over. Can anyone please help me out?
Keeping it simple, it is a module that reads input from the user, but with a twist, it has a timeout placed by the developer, if the program doesn't detect the information from the user, it skips the input.
A simple way to use it would be:
timer = 2
var = inputtimeout(prompt='Enter: ', timeout=timer)
That would give the user 2 seconds to type, you can also increment with a trycatch block to give a message to the user in case of a timeout.

Is there a way to set the recursion limit to infinite in Python? [duplicate]

This question already has answers here:
What is the maximum recursion depth in Python, and how to increase it?
(19 answers)
Closed 4 years ago.
So I was trying to make a simple program that would calculate the sum of the harmonic series and then print the results. But then the recursion limit stops it from going on.
Here is the program:
def harm_sum(n):
if n < 2:
return 1
else:
return (1 / n) + (harm_sum(n - 1))
x = 1
while True:
print(x, harm_sum(x))
x += 1
I want the program to keep on running despite the recursion limit is there a way to do that?
Direct answer: No, you cannot disable the stack limit; it's there to avoid using up all the available stack space, which would crash your run without any Traceback information.
Also, note that it's not possible to have an infinite stack size: each stack frame occupies RAM; you'll eventually run out and crash the system.
Workaround: If you can handle a hard crash, then simply use sys.setrecursionlimit to set it beyond the physical limits of your system (which are system-dependent).
Real solution: as Juan already noted, you can simply re-code your recursion as a loop.

function start to run in the first second of the minute [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want a function start to run in the first second of the minute but i can't do it
this is my code
import datetime
now = datetime.datetime.now()
while not (now.second == "01"):now = datetime.datetime.now()
Your code doesn't work because you're comparing a number (now.second) to a string "01". In Python numbers and their string representations are not equal (unlike some other programming languages), so this will never work.
Try comparing with 1 (or maybe 0 if you really want the top of the minute). And maybe instead of busy-looping (which will use all of one core of your CPU while waiting), you should perhaps instead use time.sleep to wait until the start of the next minute.
import datetime
import time
now = datetime.datetime.now()
sec = now.second
if sec != 0:
time.sleep(60-sec)
# it should be (close to) the top of the minute here!
There's always some unpredictability when dealing with time on a computer, since your program might be delayed from running by the OS at any moment (more likely if your CPU is very busy). I'd not worry about it too much though, likely it's good enough to be very close to the right time.
import time
while True:
if time.strftime("%S") == "01":
#Run Your Code
time.sleep(59)
That would pound your system like crazy, give it a little room to breathe:
import time
while True:
current_seconds = time.gmtime().tm_sec
if current_seconds == 1:
print("The first second of a minute...")
time.sleep(0.9) # wait at least 900ms before checking again
You can further streamline it by calculating how much time to wait before you start checking again - if you're interested only in the first second you can safely sleep until the end of the minute.

Pausing a while loop [duplicate]

This question already has answers here:
How do I make a time delay? [duplicate]
(13 answers)
Closed 8 years ago.
I have a query for a small program that I am running. I was wondering if there was any way to pause a while loop in python for an amount of time? Say for example if I wanted it to print something out, then pause for say (1) second, then print it out again?
There is not really a point to this program I am more doing it for something to do while bored.
I have checked other questions and none seemed to really answer what I was asking.
import time
while ...
print your line
time.sleep(1) # sleep for one second
time sleep method
Yes. There is a function called sleep that does exactly what you want:
while true:
print "Hello!\n"
time.sleep(1)

Categories