I want a piece of code that stops exactly in one second
note using time.sleep() does not do the job precisely
here is what I have so far(that doesn't give me precise result)
import time
import sys
start_time = time.time()
time.sleep(.99483-(time.time() - start_time))
print(time.time() - start_time)
sys.exit(0)
also note that the final time should include the last line which is sys.exit(0) execution
I appreciate any help or advice you could spear
import time
import sys
start_time = time.time()
while time.time() - start_time < 1:
pass
print(time.time() - start_time)
Try this and let me know if this meets your requirement
Related
How do I print the time every 10 seconds based off of using the % operator and the datetime package? This only prints once...
from datetime import datetime, timezone, timedelta
import time
now_utc = datetime.now(timezone.utc)
while True:
if (now_utc - datetime.now(timezone.utc)).total_seconds() % 10 == 0:
print(time.ctime())
In response to comments on the question: you can do this without datetime and %. The benefit is that it's much simpler.
import time
POLLING_PERIOD = 0.1 # seconds
if __name__ == '__main__':
prev_time = time.time()
print(time.ctime())
while True:
cur_time = time.time()
if cur_time - prev_time >= 10:
prev_time = cur_time
print(time.ctime())
time.sleep(POLLING_PERIOD)
This script gets the seconds from Unix epoch and prints the current time every 10s. You can adjust the polling period to minimize spinning and ensure that the time is printed only every 10s, rather than 11s, 12s, etc. due to poor resolution.
Please note that this script is susceptible to drift due to inaccuracy of time.sleep() and will eventually print a time which is greater than 10s since the last printed time.
After running some experiments on a system with low load, time.sleep() performs very well over several hours if the sleep time is adjusted based on the difference between the previous and current times.
import time
REPORTING_INTERVAL = 10 # seconds
if __name__ == '__main__':
prev_time = time.time()
sleep_time_adj = 0
print(time.ctime())
while True:
time.sleep(REPORTING_INTERVAL - sleep_time_adj)
print(time.ctime())
cur_time = time.time()
sleep_time_adj = cur_time - prev_time - REPORTING_INTERVAL
prev_time = cur_time
It really comes down to how accurate this needs to be, how long it's going to run, and the system it will run on.
i need your help.
I need a non-bloking timer, that allows me, in the period it's still counting, doing other tasks.
I need this function for my bot and obviously I don't want to block it all times I call this type of function which requires these timers.
So, in the past i used to use in Arduino (c++) the function millis() that in the same configuration seems not working well like
int t0 =0
int t1
void loop(){
t1= millis()
while (t1-t0 < 6000){
Serial.print(Timer!);
t0 = millis();}}
Do you have any advice for me? A code where I can start from?
Thanks!
The following will print "Timer" for 6 seconds:
import time
start_time = time.time() # returns number of seconds passed since epoch
current_time = time.time()
max_loop_time = 6 # 6 seconds
while (current_time - start_time) <= max_loop_time:
# do stuff
print("Timer")
current_time = time.time()
Okay, i found the solution by myself, trying to remember what i previously did on Arduino.
I based this answer from Adam Minas's one, but mine is quite different
So the expected behavior had to be:
print(something) every 5 seconds so:
import time
start_time = time.time() # returns number of seconds passed since epoch
#current_time = time.time()
print(start_time)
max_loop_time = 20 # 6 seconds
while True:
while (time.time() - start_time) > max_loop_time:
print("Timer")
start_time = time.time()
Then you can stop your while loop with break and other functions like
if == smth :
break
i have this script but counts from seconds while the scripts ends in less than a second.
import time
start = time.time()
p=[1,2,3,4,5]
print('It took {0:0.1f} seconds'.format(time.time() - start))
python 3.7 uses a new function that can do that. I have 3.6.5. How do i do that?
time.perf_counter(), available since Python 3.3, lets you access a high-resolution wallclock.
t0 = time.perf_counter()
time.sleep(.1)
print(time.perf_counter() - t0)
It doesn't count in seconds. It counts in fractions of a second, it's just that the script ends faster than the precision allowed by the string formatted float, ie. much less than a second.
Try:
import time
start = time.time()
p=[1,2,3,4,5]
time.sleep(0.5)
print('It took {0:0.1f} seconds'.format(time.time() - start))
Also, for shorter sleep you may want to increase the precision of your float formatter (eg {0:0.3f}), so that for shorter sleeps (eg 0.007) you don't have a 0.0 printed to console.
import time
start = time.time()
p=[1,2,3,4,5]
time.sleep(0.007)
print('It took {0:0.3f} seconds'.format(time.time() - start))
Or just remove the formatter entirely (As commented by Inder):
import time
start = time.time()
p=[1,2,3,4,5]
time.sleep(0.007)
print ('It took ' + str(time.time()-start) + ' seconds')
See here for more details of timer resolution: https://docs.python.org/2/library/time.html
I bet this has been asked before but I must be searching the wrong things because i can't find anything. I have created a simple game that gives the user simple math problems that they then must answer. I want to time how long it takes them to answer these.
So basically i want a startTimer() at the beginning of my code, and a stopTimer() at the end of my code and have the time that has elapsed be saved as a variable.
If you just want difference, use time.clock() or time.time() from the time module.
import time
t1 = time.clock() # or t1 = time.time()
...
t2 = time.clock() # or t2 = time.time()
elapsedTime = t2 - t1
Refer to https://docs.python.org/2/library/time.html
t1 = time.time()
raw_input("enter your guess")
print("You took {} to answer".format(time.time() - t1))
Running it on Ubuntu 14 with Python 2.7.6
I simplified script to show my problem:
import time
import multiprocessing
data = range(1, 3)
start_time = time.clock()
def lol():
for i in data:
print time.clock() - start_time, "lol seconds"
def worker(n):
print time.clock() - start_time, "multiprocesor seconds"
def mp_handler():
p = multiprocessing.Pool(1)
p.map(worker, data)
if __name__ == '__main__':
lol()
mp_handler()
And the output:
8e-06 lol seconds
6.9e-05 lol seconds
-0.030019 multiprocesor seconds
-0.029907 multiprocesor seconds
Process finished with exit code 0
Using time.time() gives non-negative values (as marked here Timer shows negative time elapsed)
but I'm curious what is the problem with time.clock() in python multiprocessing and reading time from CPU.
multiprocessing spawns new processes and time.clock() on linux has the same meaning of the C's clock():
The value returned is the CPU time used so far as a clock_t;
So the values returned by clock restart from 0 when a process start. However your code uses the parent's process start_time to determine the time spent in the child process, which is obviously incorrect if the child processes CPU time resets.
The clock() function makes sense only when handling one process, because its return value is the CPU time spent by that process. Child processes are not taken into account.
The time() function on the other hand uses a system-wide clock, and thus can be used even between different processes (although it is not monotonic, so it might return wrong results if somebody changes the system time during the events).
Forking a running python instance is probably faster then starting a new one from scratch, hence start_time is almost always bigger then the value returned by time.clock().
Take into account that the parent process also had to read your file on disk, perform the imports which may require reading other .py files, searching directories etc.
The forked child processes don't have to do all that.
Example code that shows that the return value of time.clock() resets to 0:
from __future__ import print_function
import time
import multiprocessing
data = range(1, 3)
start_time = time.clock()
def lol():
for i in data:
t = time.clock()
print('t: ', t, end='\t')
print(t - start_time, "lol seconds")
def worker(n):
t = time.clock()
print('t: ', t, end='\t')
print(t - start_time, "multiprocesor seconds")
def mp_handler():
p = multiprocessing.Pool(1)
p.map(worker, data)
if __name__ == '__main__':
print('start_time', start_time)
lol()
mp_handler()
Result:
$python ./testing.py
start_time 0.020721
t: 0.020779 5.8e-05 lol seconds
t: 0.020804 8.3e-05 lol seconds
t: 0.001036 -0.019685 multiprocesor seconds
t: 0.001166 -0.019555 multiprocesor seconds
Note how t is monotonic for the lol case while goes back to 0.001 in the other case.
To add a concise Python 3 example to Bakuriu's excellent answer above you can use the following method to get a global timer independent of the subprocesses:
import multiprocessing as mp
import time
# create iterable
iterable = range(4)
# adds three to the given element
def add_3(num):
a = num + 3
return a
# multiprocessing attempt
def main():
pool = mp.Pool(2)
results = pool.map(add_3, iterable)
return results
if __name__ == "__main__": #Required not to spawn deviant children
start=time.time()
results = main()
print(list(results))
elapsed = (time.time() - start)
print("\n","time elapsed is :", elapsed)
Note that if we had instead used time.process_time() instead of time.time() we will get an undesired result.