I have a program which includes execution of time based while loop. Some thing like..
import time
endtime=time.time()+60.0 #1minute
while (time.time()<endtime):
do something
I was just wondering if this is possible using for loop? Can I build a time based for loop in python?
From https://wiki.python.org/moin/ForLoop
When do I use for loops?
For loops are traditionally used when you have a piece of code which you want to repeat n number of times. As an alternative, there is the WhileLoop, however, while is used when a condition is to be met, or if you want a piece of code to repeat forever, for example -
The while loop feels more natural for this task, because the for needs an enumerable or a generator.
But if you really want to do it with a for loop, I guess you can construct a generator that yields something until time.time()<endtime:
def there_is_more_time(e)
while time.time() < e:
yield True
for i in there_is_more_time(endtime):
do something
But as you see, you are again using while behind the scenes.
Perhaps someone can manage to not use the while inside the generator, but what's the point of doing so?
Sure. Here's an iterator that gives you the time since start over and over until it reaches the end:
def time_counter(seconds):
starttime = time.time()
while True:
now = time.time()
if now > starttime + seconds:
break
yield now - starttime
for t in time_counter(20):
print(t)
time.sleep(3)
When I run this, it outputs:
9.5367431640625e-07
3.002220869064331
6.0040669441223145
9.004395961761475
12.006848812103271
15.009617805480957
18.011652946472168
If you need some different value, just change the yield expression.
If you don't need any value… then you don't need a for statement; your existing code is already perfectly readable, and a for loop that iterates over and discards some meaningless values is just going to make it confusing.
Perhaps you want to create a scheduler object?
https://docs.python.org/2/library/sched.html
import sched, time
s = sched.scheduler(time.time, time.sleep)
def print_time():
print "From print_time", time.time()
def print_some_times():
print time.time()
s.enter(1, 1, print_time, ())
s.enter(2, 1, print_time, ())
s.enter(3, 1, print_time, ())
s.enter(4, 1, print_time, ())
s.enter(5, 1, print_time, ())
s.run()
print time.time()
Output:
1430392956.35
From print_time 1430392957.35
From print_time 1430392958.35
From print_time 1430392959.35
From print_time 1430392960.35
From print_time 1430392961.35
1430392961.35
Related
I have a pretty specific problem. I want to measure execution time of the generator loop (with the yield keyword). However, I don't know in what intervals next() will be called on this generator. This means I can't just get the timestamp before and after the loop. I thought getting the timestamp at the beginning and end of each iteration will do the trick but I'm getting very inconsistent results.
Here's the test code:
import time
def gen(n):
total = 0
for i in range(n):
t1 = time.process_time_ns()
# Something that takes time
x = [i ** i for i in range(i)]
t2 = time.process_time_ns()
yield x
total += t2 - t1
print(total)
def main():
for i in gen(100):
pass
for i in gen(100):
time.sleep(0.001)
for i in gen(100):
time.sleep(0.01)
if __name__ == '__main__':
main()
Typical output for me looks something like this:
2151918
9970539
11581393
As you can see it looks like the delay outside of the loop somehow influences execution time of the loop itself.
What is the reason of this behavior? How can I avoid this inconsistency? Maybe there's some entirely different way of doing what I'm trying to achieve?
You can switch the yield x and total += t2 - t1 lines to only count the time it takes to create x.
For more in dept also see: Behaviour of Python's "yield"
I want a timer, but I want it to just affect one function, so it can't just be
sleep().
For example:
def printSomething():
print("Something")
def functionWithTheTimer():
for i in range(0, 5):
#wait for 1 second
print("Timer ran out")
Say the first function is called when a button is clicked, and the second function should print something out every second, both should act independently.
If I used sleep(), I couldn't execute the first function within that one second, and that's a problem for me. How do I fix this?
For your timer function, you may want to do something like this:
def functionWithTheTimer():
for i in reversed(range(1, 6)):
print(i)
time.sleep(1)
print("finished")
This will print the range backwards (like a countdown), one number every second.
EDIT: To run a function during that time, you can just duplicate and shorten the wait time. Example:
def functionWithTheTimer():
for i in reversed(range(1, 6)):
print(i)
time.sleep(0.5)
YourFunctionHere()
time.sleep(0.5)
print("finished")
You can play with the timings a little so you can get your appropriate output.
You can use the datetime library like this:
from datetime import datetime
def functionwithtimer():
start_time = datetime.now()
# code stuff you have here
print("This function took: ", datetime.now() - start_time)
I want to make a function that prints a statement every 2 minutes. I'm really new to Python and don't fully understand the time library. This is the code I have so far:
from datetime import datetime
import time
now = datetime.now()
print now.second
print "start"
while True:
print "while loop started"
if (now % 2 == 0):
print "Hello"
else:
break
How can I do this?
You can use time.sleep here. Since you want a timer for 2 minutes, pass 120 (seconds) as the argument value.
Basically, this translates into something like below:
while True:
time.sleep(120)
print "Hello"
This will print "Hello" every 2 minutes.
Note that time.sleep is not entirely accurate, and may be off by a small but arbitrary amount of time because of OS scheduling of other processes etc and execution of the code itself.
Use the sched module
import sched, time
s = sched.scheduler(time.time, time.sleep)
def do_something(sc):
print "Doing stuff..."
# do your stuff
sc.enter(60, 1, do_something, (sc,))
s.enter(60, 1, do_something, (s,))
s.run()
take a look here.
I have some problem here. I want to stop the print command at desired time. I figured out some codes and it still keep looping. Here the code,
import time
t = time.strftime("%H%M%S")
while ti:
print(time.strftime("%H%M%S"))
time.sleep(1)
if t = ("140000"): #just example of time to stop print
break
Thanks
t = time.strftime("%H%M%S")
is only executed once before the loop, so t's value doesn't ever change.
Your approach is the worst method of checking time difference; python's datetime framework allows for subtraction of timestamps and thus, you can check the time since something else happened easily without doing any string comparisons...
This will work
import time
t = time.strftime("%H%M%S")
while t:
t = time.strftime("%H%M%S")
print(time.strftime("%H%M%S"))
time.sleep(1)
if t == ("140000"): #just example of time to stop print
break
You had some bugs in your code
while ti: -- > while t:
if t = ("140000"): --> if t== ("140000"):
and you were missing this line t = time.strftime("%H%M%S")
time.sleep(1) may sleep less or more than a second therefore t == "140000" is not enough.
To stop a loop at a given local time:
import time
from datetime import datetime
stop_dt = datetime.combine(datetime.now(), datetime.strptime("1400", "%H%M").time())
stop_time = time.mktime(stop_dt.timetuple())
while time.time() < stop_time:
print(time.strftime("%H%M%S"))
time.sleep(max(1, (stop_time - time.time()) // 2))
time.time() returns "seconds since the epoch" -- unlike strings comparison it works across a midnight.
The sleep interval is a half of the remaining time or one second (whatever larger).
time.mktime() may return a wrong result if stop time is during an end-of-DST transition ("fall back") when the local time is ambiguous (the string-based solution may stop twice in this case).
Try this:
import time
while ti:
t = time.strftime("%H%M%S")
print(time.strftime("%H%M%S"))
time.sleep(1)
if t = ("140000"): #just example of time to stop print
break
(Python 2.7.8, Windows)
there is so many questions already about this particular subject, but I cannot seem to get any of them working.
So, what I'm trying to accomplish is timing how long a function takes to execute.
I have functions.py and main.py in following fashion:
#functions.py
def function(list):
does something
return list
...
#main.py
import functions
...stuff...
while:
list = gets list from file
functions.function(list) <--- this needs to get timed
Now I tried time.time() the start and end points first, but it's not accurate enough (difference tends to be 0.0), and after some googling it seems that this isn't the way to go anyway. Apparently what I should use(?) is timeit module. However I cannot understand how to get the function into it.
Any help?
As you mentioned, there's a Python module made for this very task, timeit. Its syntax, while a little idiosyncratic, is quite easy to understand:
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000)
stmt is the function call to be measured, in your case: functions.function(list)
setup is the code you need to create the context necessary for stmt to execute, in your case: import functions; list = gets list from file
number is how many time timeit would run stmt to find its average execution time. You might want to change the number, since calling your function a million times might take a while.
tl;dr:
timeit.timeit(stmt='functions.function(list)', setup='import functions; list = gets list from file', number=100)
you see this demo: time.time
>>> def check(n):
... start = time.time()
... for x in range(n):
... pass
... stop = time.time()
... return stop-start
...
>>> check(1000)
0.0001239776611328125
>>> check(10000)
0.0012159347534179688
>>> check(100)
1.71661376953125e-05
the above function returns hum much time in sec taken by for for n loops.
so the algorithm is:
start = time.time()
# your stuff
stop = time.time()
time_taken = stop - start
start = timeit.default_timer()
my_function()
elapsed = timeit.default_timer() - start