While loop, have two if i in statements - python

OK so two questions here.
First,I am trying to show start time. I am doing this with program_time. Second, I also want to show elapsed time. I would also like to show this in microseconds.
import time
a= time.time()
print a
while True:
program_time= time.time()
elapsed=program_time - a
for i in [program_time]:
print "%s\r" % i,
Thanks in advance.

Your code looks almost correct. This should show the start time, and each subsequent program time as the while loop proceeds (albeit very quickly). Perhaps you need to perform some calculation in the loop?
import time
a = time.time()
print "Starting time is %s" % str(a)
while True:
# Clear the screen each iteration to "recycle" the lines
print chr(27) + "[2J"
program_time = time.time();
elapsed = int(round((program_time - a) * 1000)) * 100
print "Start time is %s" % a
print "Elapsed time is %s" % elapsed
# Simulate some work
time.sleep(1)

Assuming your question is "why does my program output the current time instead of the elapsed time," the answer is "because program_time is being printed rather than elapsed."

Related

Forecast the remaining time of a loop

Good Evening,
I am trying to estimate the remaining time to the end of a loop; I've used:
start = datetime.now()
progress = 0
for i in range(1000):
#do a few calculations
progress += 1
stop = datetime.now()
execution_time = stop-start
remaining = execution_time * ( 1000 - progress )
print("Progress:", progress, "%, estimated", remaining, "time remaining")
But it does not seem to work properly, since it goes up to minutes, even though the loop would take 20 seconds in total, and decrease quickly when reaching the end.
How can I try to forecast the remaining time of a loop efficiently and correctly?
Simply use tqdm package:
from tqdm import tqdm
for i in tqdm(range(10000)):
dosomthing()
It will print everything for you:
76%|█████████████ | 7568/10000 [00:33<00:10, 229.00it/s]
Rather than using datetime.datetime.now() for this sort of thing you can use time.perf_counter(), which is available in Python 3.3+. From the docs:
Return the value (in fractional seconds) of a performance counter,
i.e. a clock with the highest available resolution to measure a short
duration. It does include time elapsed during sleep and is
system-wide. The reference point of the returned value is undefined,
so that only the difference between the results of consecutive calls
is valid.
Also, you can print using a carriage return instead of a newline so that the progress reports are printed on a single line. Here's a brief demo derived from your code.
from time import sleep, perf_counter
fmt = " Progress: {:>3}% estimated {:>3}s remaining"
num = 1000
start = perf_counter()
for i in range(1, num + 1):
# Simulate doing a few calculations
sleep(0.01)
stop = perf_counter()
remaining = round((stop - start) * (num / i - 1))
print(fmt.format(100 * i // num, remaining), end='\r')
print()
Depending on your terminal (and Python version) you may also need to add the flush=True keyword arg to the print call in order to get the progress reports to print as they are issued.
I think that in this line:
remaining = execution_time * ( 1000 - progress )
you should divide execution_time/progress, because you want to know how long it takes to complete one percent of progress.
remaining = execution_time/progress * ( 1000 - progress )
Your calculation for time remaining is wrong. If it takes execution_time for progress steps. Then how much does it take for 1000 steps ?
Simple cross multiply gives you the total time. Subtract it from the time already elapsed and that will give you the time remaining.
remaining_time = execution_time * 1000 / progress - execution_time
percent_complete = (progress / 1000) * 100 #You can simplify this if you like
print("Progress:", percent_complete , "%, Estimated", remaining_time, "time remaining")
Also your variable execution_time_1 is never defined

Timing how long it takes

i'm making a simple code about divisors and I'd like to have a feedback on how long it takes for the computer to give me an answer.
Here's my code:
num=int(input('Give me a number'))
listRange=list(range(1,num+1))
divisorList=[]
for number in listRange:
if num%number==0:
divisorList.append(number)
print(divisorList)
As you can see, the bigger the number, more time the computer takes to process all the divisors, so I wanna know how much time it spends whilst doing that.
You can use the time module to a timestamp before the loop and another after and print the difference.
import time
num=int(input('Give me a number'))
listRange=list(range(1,num+1))
divisorList=[]
start = time.time() # use time.clock() if on Windows
for number in listRange:
if num%number==0:
divisorList.append(number)
end = time.time() # use time.clock() if on Windows
print(divisorList)
print("Time taken: {:06.5f}secs".format(end-start)) # Seconds
print("Time taken: {:10.5f}ms".format((end-start)*1000) # Miliseconds
If you want to find the time in seconds:
from time import time
start = time()
... # code
print(time() - start)
You could use the timeit module:
import timeit
num=100000
listRange=list(range(1,num+1))
def function():
divisorList=[]
for number in listRange:
if num%number==0:
divisorList.append(number)
print(timeit.timeit(function, number=1))
# 0.01269146570884061

Python: Rounding output of the time module

This is the code I have for measuring how long it took the user to complete the program:
start_time = time.time() # Sits at the top of my code
print("%f seconds" % (time.time() - start_time)) # Goes at the bottom of my code
My question is, how do I round the output of this to one decimal place? For example, if my output was 3.859639 seconds how would I present this like: 3.8 Secounds?
It looks like you've forgotten ".1" before "f". Try this:
print("%.1f seconds" % (time.time() - start_time))
Use round function with second argument as 1
start_time = time.time() # Sits at the top of my code
x=round((time.time() - start_time),1)
print x
Primitive way... multiply out, truncate the rest, then divide again:
diff = time.time() - start_time
rounded_down = int(diff * 10) / 10 # = 3.8

Display a countdown for the python sleep function

I am using time.sleep(10) in my program. Can display the countdown in the shell when I run my program?
>>>run_my_program()
tasks done, now sleeping for 10 seconds
and then I want it to do 10,9,8,7....
is this possible?
you could always do
#do some stuff
print 'tasks done, now sleeping for 10 seconds'
for i in xrange(10,0,-1):
time.sleep(1)
print i
This snippet has the slightly annoying feature that each number gets printed out on a newline. To avoid this, you can
import sys
import time
for i in xrange(10,0,-1):
sys.stdout.write(str(i)+' ')
sys.stdout.flush()
time.sleep(1)
This is the best way to display a timer in the console for Python 3.x:
import time
import sys
for remaining in range(10, 0, -1):
sys.stdout.write("\r")
sys.stdout.write("{:2d} seconds remaining.".format(remaining))
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("\rComplete! \n")
This writes over the previous line on each cycle.
A simple solution that clears the last number from the console:
import time
for i in range(10,0,-1):
print(f"{i}", end="\r", flush=True)
time.sleep(1)
By default, the print function sets end="\n" which means subsequent calls to print will be printed on a new line. You can change this to end="\r" to replace the output after each call. (How does carriage return "\r" work in python).
Here f"{i}" is for printing single digit only. You can modify it based on number of digits.
e.g. Here it will work for two digits by just adding one space as a postfix- f"{i} "
Also, using flush means you don't have to worry about buffering issues. (What does print()'s flush do?)
This is how it looks:
You can do a countdown function like:
import sys
import time
def countdown(t, step=1, msg='sleeping'): # in seconds
pad_str = ' ' * len('%d' % step)
for i in range(t, 0, -step):
print '%s for the next %d seconds %s\r' % (msg, i, pad_str),
sys.stdout.flush()
time.sleep(step)
print 'Done %s for %d seconds! %s' % (msg, t, pad_str)
The carriage return \r and the comma , will keep the print in the same line (avoiding one line for each countdown value)
As the number of seconds decreases, the pad_str will ensure the last line is overwritten with spaces instead of leaving the last character(s) behind as the output shortens.
The final print overwrites the last status message with a done message and increments the output line, so there is evidence of the delay.
This is something that I've learned at one of my first python lessons, we played with ["/","-","|","\","|"] but the principle is the same:
import time
for i in reversed(range(0, 10)):
time.sleep(1)
print "%s\r" %i,
time.sleep() may return earlier if the sleep is interrupted by a signal or later (depends on the scheduling of other processes/threads by OS/the interpreter).
To improve accuracy over multiple iterations, to avoid drift for large number of iterations, the countdown may be locked with the clock:
#!/usr/bin/env python
import sys
import time
for i in reversed(range(1, 1001)):
time.sleep(1 - time.time() % 1) # sleep until a whole second boundary
sys.stderr.write('\r%4d' % i)
Here's one I did:
import time
a = input("How long is the countdown?")
while a != 0:
print a
time.sleep(1)
a = a-1
At the end if you and an else you can put an alarm or whatever.
Sure, just write a loop that prints 10 minus the iteration counter, then have it sleep 1 second each iteration and run for 10 iterations. Or, to be even more flexible:
def printer(v):
print v
def countdown_timer(duration, step=1, output_function=printer,
prompt='Waiting {duration} seconds.'):
output_function(prompt.format(duration=duration))
for i in xrange(duration/step):
output_function(duration - step * i)
Another easy way, without reinventing the wheel, is to use tqdm, which automatically displays a progress bar:
from time import sleep
from tqdm import tqdm
for _ in tqdm(range(10)):
sleep(1)
Optionally, you can then modify the display of the loading bar as you wish.
This one is subsecond precise:
print()
_k = 0.5 # ensure k != _k first time round (as k will be integer)
print('Starting in ')
while _k > 0:
k = round(event_timestamp - time())
if k != _k:
print(f'\r{k} ', end='', flush=True)
_k = k
sleep(0.1)
print('boom')
Notice the trailing space in f'\r{k} '. So if we go from 100 to 99 or 10 to 9 it clears the second digit.
Also it doesn't require import sys.
sleep(0.0003) if you want millisecond precision.
if you don't limit yourself to sleep, then (courtesy automatetheboringstuff), pyautogui has a nifty countdown function:
import pyautogui
print('Starting in ', end=''); pyautogui.countdown(3)
may be this will help
import turtle
for i in range(10):
t2 = turtle.Turtle()
t2.hideturtle()
t2.penup()
t2.goto(0,0)
t2.write(i,font=("Arial", 16, "normal"))
i-=1
sleep(1)
t2.clear()

Time measure script in python

I received the following script from a fellow programmer:
from time import *
start = strptime(asctime())
end = strptime(asctime())
print 'you took %i minutes' % (end[4] - start[4])
As you might already know, the script measures the time between the third and fourth line. However, it seems to measure it in minutes. How can I go about to measure it in seconds, with at least one decimal place (ex. 7.4 seconds).
Also, I would like to add one extra piece of functionality. Say the script runs, and I am asked by the program to type any word. At the end of my typing, I have to press the enter key to exit the program and measure the time from the first keystroke to the moment I press enter. How can I go about measuring this?
First, I would avoid using import * as it's considered bad practice. You can use time.time() to get more precision:
>>> import time
>>> start = time.time()
>>> end = time.time()
>>> end - start
5.504057168960571
You could also use datetime.datetime.now().
#source: http://docs.python.org/library/timeit.html
def test():
"""Stupid test function"""
L = []
for i in range(100):
L.append(i)
if __name__ == '__main__':
from timeit import Timer
t = Timer("test()", "from __main__ import test")
print t.timeit()
If you are trying to optimize a python web service call, you can do the following.
import time
In the beginning of the function, right
start = time.time()
in the line put (540 is the line number),
l540 = time.time()
print("--------l541 ------------")
print(l540 - start)
in the next line put (608 is the line number),
l608 = time.time()
print("-------- 609 ------------")
print(l608 - l540)
You can add as many as you want and it will tell you where exactly the program is taking time.

Categories

Resources