Timing how long it takes - python

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

Related

Show how long does it take for the script to be completed

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!

Python - Print index of for loop only once every five minutes

I'm trying to get a for loop to print the value of 'i' every 5 minutes
import threading
def f(i):
print(i)
threading.Timer(600, f).start()
for i in range(1,1000000000000):
f(i=i)
However, this method results in the code printing the value of i instantly since it calls 'f' as soon as it finds 'i'.
I know this is not the first time someone will ask, nor the last, but I can't get it to work on a for loop nested within a function.
I'm fairly new to Python and I'd appreciate any help.
How about just keeping track of how long has passed in the loop?
from timeit import default_timer as timer
start = timer()
freq = 5 * 60 # Time in seconds
last_time = 0.0
for i in range(int(1e8)):
ctime = timer()
if ctime - last_time > freq:
print(i)
last_time = ctime
I imagine you can make this more efficient by only checking the time every N iterations rather than every time. You may also want to look into using progressbar2 for a ready-made solution.
I prefer using datetime, as I think it's more intuitive and looks a bit cleaner. Otherwise, using more or less the same approach as Paul:
from datetime import datetime, timedelta
print_interval = timedelta(minutes=5)
# Initialize the next print time. Using now() will print the first
# iteration and then every interval. To avoid printing the first
# time, just add print_interval here (i.e. uncomment).
next_print = datetime.now() # + print_interval
for i in range(int(1e8)):
now = datetime.now()
if now >= next_print:
next_print = now + print_interval
print(i)
Also note that before python 3.x xrange would be preferable over range.

Displaying algorithm run time in python

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

Measuring user acting time in python

So I have a script where it measures how fast a person can press the keyboard 100 times. I have used the time module to set the start and the end of the measuring:
import time
import os
start = time.time()
pause() * 100 #defined the definition to os.system("pause")
end = time.time()
How do I make it so python can compare the elapsed time so if the time taken is >20seconds, it performs commands, and if it is equal or less than 20 seconds then preforms other commands?
You mean like this?
elapsed_time = end - start
if elapsed_time > 20:
# code
else:
# other code

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