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
Related
I wrote a python code like this
total = 500
a = 0
for i in range(500):
a += 1
And I want to show something like the photo i uploaded in terminal
Is there a module that can do this for me?
or How can I do this?
Use time module
import time
start_time = time.time()
main()
print("--- %s seconds ---" % (time.time() - start_time))
I do not know much about any libraries that support progress bars like one in your attached photo.
However, for timing your code, the best two options from the Python Standard Library are from the time and timeit module.
From the time module (documentation), you should use time.perf_counter() (unit of time = seconds) or time.perf_counter_ns() (unit of time = nanoseconds, helps combat precision loss due to float in perf_counter). These are recommended/preferred over time.time() for the purposes of timing code.
Example usage:
import time
def foo(x):
return x * x
if __name__ == '__main__':
# not meaningful on it's own
start_time = time.perf_counter_ns()
# a very silly example, but for illustration
foo(5)
# not meaningful on it's own
end_time = time.perf_counter_ns()
# taking difference meaningful
print(f"Time elapsed: {end_time - start_time} nanoseconds")
Output
Time elapsed: 581 nanoseconds
The timeit module (documentation) is well-suited for timing small chunks of Python code. Using the code you provided, here is an example:
import timeit
def foo():
total = 500
a = 0
for i in range(500):
a += 1
if __name__ == '__main__':
print(timeit.timeit("foo()", setup="from __main__ import foo", number=100000))
Output
1.2454171699937433
indicating it took about 1.245 seconds to execute foo() 100,000 = number times. number can be changed to whatever you want.
Hope this helps!
I have 1 time that is formatted like this
start_time 01:13:05
I have a second time that looks like it
Current time 01:13:10
When I calculating the difference, it produces the correct answer but chops a zero off
code:
new_start_time = datetime.strptime(start_time, '%H:%M:%S')
new_current_time = datetime.strptime(str(current_time), '%H:%M:%S')
elapsed_time = new_current_time - new_start_time
produces:
elapsed time 0:00:10
The 10 is correct but what happened to the zero? How do I hack it back on? I need it.
Add:
elapsed_split = str(elapsed_time).split(":")
elapsed_time = int(elapsed_split[0]).zfill(2) + elapsed_split[1:]
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
I am required to display the time it took to run two different algorithms using functions available in the time library. I'm assuming I have to use the timeit() function however I'm not familiar as to how to incorporate that into the code. So far this is what I have:
import time
def time2Algorithms(sound):
# normalize(sound)
largest = 0
for s in getSamples(sound):
largest = max(largest,getSampleValue(s) )
multiplier = 32767.0 / largest
for s in getSamples(sound):
louder = multiplier * getSampleValue(s)
setSampleValue(s,louder)
explore(sound)
# onlyMaximize(sound)
for sample in getSamples(sound):
value = getSampleValue(sample)
if value >= 0:
setSampleValue(sample,32767)
if value < 0:
setSampleValue(sample,-32768)
explore(sound)
My goal is to display the run times of both the normalize and maximize algorithms after they execute.
Thanks.
The time module (which you are required to use) does not include timeit (different module).
Just add a
start = time.time()
just before the part you want to time, and e.g
print(time.time() - start)
just after said part -- this will display the elapsed time in seconds. Ornament and format that as required, of course:-)
You can use timeit like this
import timeit
start_time = timeit.default_timer()
# Your algo goes here
elapsed = timeit.default_timer() - start_time
and also time module which is easy
import time
start_time = time.time()
# Your algo goes here
elapsed = time.time() - start_time
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."