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))
Related
I am trying to measure the execution time of a Python program. For this, I am using the perf_counter() library.
My problem is not with respect to the library, but with respect to how to measure a concrete case.
The thing is that my program contains a while, and I am particularly interested in knowing how much execution time the while's condition consumes (for those interested: this is because the condition of the while is that a very long logical formula is satisfiable, so this sat search can be expensive).
My question is, how can I calculate this?
I mean, I could (as you can see below) re-execute the condition and save it but that is not a solution for me because (1) the time could have been different from that of the execution of the while condition and, above all, (2) it would be preferable not to re-execute code, as this falsifies the real time of the total execution.
t_start = perf_counter()
...
t_condition = 0
while condition:
t_conditionStart = perf_counter()
condition #measure this one? I do not like this!
t_conditionStop = perf_counter()
t_condition += t_conditionStop - t_conditionStart
...
...
t_stop = perf_counter()
total_time = t_stop - t_start
condition_percentage = t_condition / total_time
I don't know if I'm missing something very basic.
For the ones interested in the real SAT problem (using Z3-Py), the code should go (or better said: should not go) like this:
t_start = perf_counter()
...
t_satSearch = 0
s = Solver()
while s.check() == sat:
t_satSearchStart = perf_counter()
s.check() == sat #measure this one? I do not like this!
t_satSearchStop = perf_counter()
t_satSearch += t_satSearchStop - t_satSearchStart
...
...
t_stop = perf_counter()
total_time = t_stop - t_start
satSearch_percentage = t_satSearch / total_time
Condition is checked before each execution of the loop. So, all you need to do is to is to measure time in 4 places:
before the loop (t0)
at the beginning of the loop (t1)
right before loop finishes (t0)
after the while loop (t1)
This way you can get the execution time in every possible case by checking what is the value of t1-t0 every time you update t1.
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 am working on a project which accurate timer is really crucial. I am working on python and am using timer.sleep() function.
I noticed that timer.sleep() function will add additional delay because of the scheduling problem (refer to timer.sleep docs). Due to that issue, the longer my program runs, the more inaccurate the timer is.
Is there any more accurate timer/ticker to sleep the program or solution for this problem?
Any help would be appreciated. Cheers.
I had a solution similar to above, but it became processor heavy very quickly. Here is a processor-heavy idea and a workaround.
def processor_heavy_sleep(ms): # fine for ms, starts to work the computer hard in second range.
start = time.clock()
end = start + ms /1000.
while time.clock() < end:
continue
return start, time.clock()
def efficient_sleep(secs, expected_inaccuracy=0.5): # for longer times
start = time.clock()
end = secs + start
time.sleep(secs - expected_inaccuracy)
while time.clock() < end:
continue
return start, time.clock()
output of efficient_sleep(5, 0.5) 3 times was:
(3.1999303695151594e-07, 5.0000003199930365)
(5.00005983869791, 10.00005983869791)
(10.000092477987678, 15.000092477987678)
This is on windows. I'm running it for 100 loops right now. Here are the results.
(485.003749358414, 490.003749358414)
(490.0037919174879, 495.0037922374809)
(495.00382903668014, 500.00382903668014)
The sleeps remain accurate, but the calls are always delayed a little. If you need a scheduler that accurately calls every xxx secs to the millisecond, that would be a different thing.
the longer my program runs, the more inaccurate the timer is.
So, for example by expecting 0.5s delay, it will be time.sleep(0.5 - (start-end)). But still didn't solve the issue
You seem to be complaining about two effects, 1) the fact that timer.sleep() may take longer than you expect, and 2) the inherent creep in using a series of timer.sleep() calls.
You can't do anything about the first, short of switching to a real-time OS. The underlying OS calls are defined to sleep for at least as long as requested. They only guarantee that you won't wake early; they make no guarantee that you won't wake up late.
As for the second, you ought to figure your sleep time according to an unchanging epoch, not from your wake-up time. For example:
import time
import random
target = time.time()
def myticker():
# Sleep for 0.5s between tasks, with no creep
target += 0.5
now = time.time()
if target > now:
time.sleep(target - now)
def main():
previous = time.time()
for _ in range(100):
now = time.time()
print(now - previous)
previous = now
# simulate some work
time.sleep(random.random() / 10) # Always < tick frequency
# time.sleep(random.random()) # Not always < tick frequency
myticker()
if __name__ == "__main__":
main()
Working on Linux with zero knowledge of Windows, I may be being naive here but is there some reason that writing your own sleep function, won't work for you?
Something like:
import time
def sleep_time():
start_time = time.time()
while (time.time() - start_time) < 0.0001:
continue
end_time = time.time() + 60 # run for a minute
cnt = 0
while time.time() < end_time:
cnt += 1
print('sleeping',cnt)
sleep_time()
print('Awake')
print("Slept ",cnt," Times")
I am new to Python. I want to add wait between two function calls.
Below is the code snap, but with this code wait is not working. My code goes in to pause as soon as it reaches the first line of uploadFullstackZiptoCDN().
How Can I make sure that I have a pause of 5 minutes between the functions?
uploadFullstackZiptoCDN(fsartifactFile,fullStackgroup_ID,fsVersion,sdpIP,cdnIP)
makeRestCalls(ugdmHostIP,ipmessagingHostIP,cdnIP,fsVersion,fsartifactFile,'FullStack')
time.sleep(300)
makeappUpgradeZip(appartifactFile,appgroup_ID,appversion,sdpIP,cdnIP)
uploadZiptoCDN(cdnIP,appartifactFile,appversion)
Code below produces a delay which seems to be well-controlled.
It might likely be adapted to your needs.
Among other differences, it allows for more granularity in the start and stop times than time.sleep.
#!/usr/bin/python3
import time
t0 = time.time()
nsecs = 300
while True :
t1 = time.time()
if ( (t1 - t0) > nsecs ) :
break
print( t1 - t0 )
I am running the following code try to measure how long my PG process finish, however, the "toc-tic" displays as soon as the whole loop finish, is there any way that I can measure the total time and time for individual thread? Thanks
tic = time.clock()
for i in range(0,2):
start = i * step
end = start + step
pg = PatternGenerator()
pg.counter = start
pg.pos = i
pg.data = lines[start:end]
pg.start()
toc = time.clock()
print toc - tic
Regards,
Andy
Join the threads, before toc!
You can put the objects to a list, then call join on them!
before the for :
pglist = []
... start the threads...
for pg in pglist:
pg.join()
toc = time.clock()
print toc - tic