Time measurement - function with an input inside - python

My task is to measure time of a function which contains an input inside (the user is to input a list).
There is the code:
import numpy
import itertools
def amount(C):
N = numpy.array(input().strip().split(" "),int)
N = list(N)
N = sorted(N)
while C < max(N):
N.remove(max(N))
res = []
for i in range(1, C):
for j in list(itertools.combinations_with_replacement(N, i)):
res.append(sum(list(j)))
m = 0
for z in range (0, len(res)):
if res[z] == C:
m += 1
if N[0] == 1:
return m + 1
else:
return m
Of course it is not optimized (but it's not the case now).
Because of the "list" standard way by which I mean:
import time
start = time.time()
amount(10)
end = time.time()
print(end - start)
does not work.
How can I measure the time? For example for:
C in range [0, 11]
N = [1, 2 , 5]
I would be grateful for any help! :)

You want somethig like this?
import time
# measure process time
t0 = time.clock()
amount(10)
print time.clock() - t0, "seconds process time"
# measure wall time
t0 = time.time()
amount(10)
print time.time() - t0, "seconds wall time"
UPDATE : The soulution maybe could be this :
times=[]
for x in range(12):
t0 = time.time()
amount(x)
times.append( time.time() - t0);
or better if you use timeit : here

What do you think about this:
import time
def time_counter(amount, n=100, M=100):
res = list(range(n))
def count_once():
start = time.perf_counter()
amount(res)
return time.perf_counter() - start
return [count_once() for m in range(M)]
It is to make M = 1000 measurements and for C in range(0, n). Is it alright?

Related

Create clock pulse with python

I want to work with exactly 20ms sleep time. When i was using time.sleep(0.02), i am facing many problems. It is not working what i want. If I had to give an example;
import time
i = 0
end = time.time() + 10
while time.time() < end:
i += 1
time.sleep(0.02)
print(i)
We wait to see "500" in console. But it is like "320". It is a huge difference. Because sleep time is not working true and small deviations occur every sleep time. It is increasing cumulatively and we are seeing wrong result.
And then, i want to create my new project for clock pulse. Is it that possible with time.time()?
import time
first_time = time.time() * 100 #convert seconds to 10 * miliseconds
first_time = int(first_time) #convert integer
first_if = first_time
second_if = first_time + 2 #for sleep 20ms
third_if = first_time + 4 #for sleep 40ms
fourth_if = first_time + 6 #for sleep 60ms
fifth_if = first_time + 8 #for sleep 80ms
end = time.time() + 8
i = 0
while time.time() < end:
now = time.time() * 100 #convert seconds to 10 * miliseconds
now = int(now) #convert integer
if i == 0 and (now == first_if or now > first_if):
print('1_' + str(now))
i = 1
if i == 1 and (now == second_if or now > second_if):
print('2_' + str(now))
i = 2
if i == 2 and (now == third_if or now > third_if):
print('3_' + str(now))
i = 3
if i == 3 and (now == fourth_if or now > fourth_if):
print('4_' + str(now))
i = 4
if i == 4 and (now == fifth_if or now > fifth_if):
print('5_' + str(now))
break
Out >> 1_163255259009
2_163255259011
3_163255259013
4_163255259015
5_163255259017
Is this project true logic? And If it is true logic, how can finish this projects with true loops?
Because i want these sleeps to happen all the time. Thank you in advice.
Let's say you want to count in increments of 20ms. You need to sleep for the portion of the loop that's not the comparison, increment, and print. Those operations take time, probably about 10ms based on your findings.
If you want to do it in a loop, you can't hard code all the possible end times. You need to do something more general, like taking a remainder.
Start with the time before the loop:
t0 = time.time()
while time.time() < end:
i += 1
Now you need to figure out how long to sleep so that the time between t0 and the end of the sleep is a multiple of 20ms.
(time.time() - t0) % 0.02 tells you how far past a 20ms increment you are because python conveniently supports floating point modulo. The amount of time to wait is then
time.sleep(0.02 - (time.time() - t0) % 0.02)
print(i)
Using sign rules of %, you can reduce the calculation to
time.sleep(-(time.time() - t0) % 0.02)

How can I make countdown time?

So I have my code here:
import time
from random import uniform
rng = uniform(1, 3)
start = time.time()
while True:
if time.time() == start + rng:
print("finally")
My question is: how can I make the program print "finally"?
add a break also ;)
import time
from random import uniform
rng = uniform(1, 3)
start = time.time()
while True:
if time.time() >= start + rng: # first edit here (also as suggested by Patrick Haugh)
print("finally")
break # add this also to skip infinite looping

Interpolate between elements in an array of floats

I'm getting a list of 5 floats which I would like to use as values to send pwm to an LED. I want to ramp smoothly in a variable amount of milliseconds between the elements in the array.
So if this is my array...
list = [1.222, 3.111, 0.456, 9.222, 22.333]
I want to ramp from 1.222 to 3.111 over say 3000 milliseconds, then from 3.111 to 0.456 over the same amount of time, and when it gets to the end of the list I want the 5th element of the list to ramp to the 1st element of the list and continue indefinitely.
do you think about something like that?
import time
l = [1.222, 3.111, 0.456, 9.222, 22.333]
def play_led(value):
#here should be the led- code
print value
def calc_ramp(given_list, interval_count):
new_list = []
len_list = len(given_list)
for i in range(len_list):
first = given_list[i]
second = given_list[(i+1) % len_list]
delta = (second - first) / interval_count
for j in range(interval_count):
new_list.append(first + j * delta)
return new_list
def endless_play_led(ramp_list,count):
endless = count == 0
count = abs(count)
while endless or count!=0:
for i in range(len(ramp_list)):
play_led(ramp_list[i])
#time.sleep(1)
if not endless:
count -= 1
print '##############',count
endless_play_led(calc_ramp(l, 3),2)
endless_play_led(calc_ramp(l, 3),-2)
endless_play_led(calc_ramp(l, 3),0)
another version, similar to the version of dsgdfg (based on his/her idea), but without timing lag:
import time
list_of_ramp = [1.222, 3.111, 0.456, 9.222, 22.333]
def play_LED(value):
s = ''
for i in range(int(value*4)):
s += '*'
print s, value
def interpol(first, second, fract):
return first + (second - first)*fract
def find_borders(list_of_values, total_time, time_per_step):
len_list = len(list_of_values)
total_steps = total_time // time_per_step
fract = (total_time - total_steps * time_per_step) / float(time_per_step)
index1 = int(total_steps % len_list)
return [list_of_values[index1], list_of_values[(index1 + 1) % len_list], fract]
def start_program(list_of_values, time_per_step, relax_time):
total_start = time.time()
while True:
last_time = time.time()
while time.time() - last_time < relax_time:
pass
x = find_borders(list_of_values,time.time(),time_per_step)
play_LED(interpol(x[0],x[1],x[2]))
start_program(list_of_ramp,time_per_step=5,relax_time=0.5)

Execution time using time.time() in Python

I wrote some code for a HackerRank problem (https://www.hackerrank.com/challenges/acm-icpc-team).
import time
from itertools import combinations
start_time = time.time()
n,m = raw_input().strip().split(' ') # n = no of people and m = no of topics
n,m = [int(n),int(m)]
topic = []
topic_i = 0
for topic_i in xrange(n):
topic_t = str(raw_input().strip())
topic.append(topic_t) # populate the topic[] list with the topics
counts = []
for list1, list2 in combinations(topic, 2):
if list1 != list2:
count = 0
for i in xrange(m):
if int(list1[i]) | int(list2[i]):
count += 1
counts.append(count)
print max(counts)
print counts.count(max(counts))
print time.time() - start_time
When I try to run the code, I get an execution time of 8.37576699257 seconds. But my program got over in a jiffy. I have read that the timeit() function, by default, runs the function passed to it a million times. Does something similar happen here?
You counted the time when the program waited for the user input too. You may want to move the first time.time() invocation below raw_input().

Python loop to run for certain amount of seconds

I have a while loop, and I want it to keep running through for 15 minutes. it is currently:
while True:
#blah blah blah
(this runs through, and then restarts. I need it to continue doing this except after 15 minutes it exits the loop)
Thanks!
Try this:
import time
t_end = time.time() + 60 * 15
while time.time() < t_end:
# do whatever you do
This will run for 15 min x 60 s = 900 seconds.
Function time.time returns the current time in seconds since 1st Jan 1970. The value is in floating point, so you can even use it with sub-second precision. In the beginning the value t_end is calculated to be "now" + 15 minutes. The loop will run until the current time exceeds this preset ending time.
If I understand you, you can do it with a datetime.timedelta -
import datetime
endTime = datetime.datetime.now() + datetime.timedelta(minutes=15)
while True:
if datetime.datetime.now() >= endTime:
break
# Blah
# Blah
Simply You can do it
import time
delay=60*15 ###for 15 minutes delay
close_time=time.time()+delay
while True:
##bla bla
###bla bla
if time.time()>close_time
break
For those using asyncio, an easy way is to use asyncio.wait_for():
async def my_loop():
res = False
while not res:
res = await do_something()
await asyncio.wait_for(my_loop(), 10)
I was looking for an easier-to-read time-loop when I encountered this question here. Something like:
for sec in max_seconds(10):
do_something()
So I created this helper:
# allow easy time-boxing: 'for sec in max_seconds(42): do_something()'
def max_seconds(max_seconds, *, interval=1):
interval = int(interval)
start_time = time.time()
end_time = start_time + max_seconds
yield 0
while time.time() < end_time:
if interval > 0:
next_time = start_time
while next_time < time.time():
next_time += interval
time.sleep(int(round(next_time - time.time())))
yield int(round(time.time() - start_time))
if int(round(time.time() + interval)) > int(round(end_time)):
return
It only works with full seconds which was OK for my use-case.
Examples:
for sec in max_seconds(10) # -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for sec in max_seconds(10, interval=3) # -> 0, 3, 6, 9
for sec in max_seconds(7): sleep(1.5) # -> 0, 2, 4, 6
for sec in max_seconds(8): sleep(1.5) # -> 0, 2, 4, 6, 8
Be aware that interval isn't that accurate, as I only wait full seconds (sleep never was any good for me with times < 1 sec). So if your job takes 500 ms and you ask for an interval of 1 sec, you'll get called at: 0, 500ms, 2000ms, 2500ms, 4000ms and so on. One could fix this by measuring time in a loop rather than sleep() ...
The best solution for best performance is to use #DrV answer and the suggestion from #jfs to use time.monotonic():
import time
from datetime import datetime, timedelta
count = 0
end_time = time.monotonic() + 10
while time.monotonic() < end_time:
count += 1
print(f'10 second result: {count=:,}')
# 10 second result: count=185,519,745
count = 0
end_time = time.time() + 10
while time.time() < end_time:
count += 1
print(f'10 second result: {count=:,}')
# 10 second result: count=158,219,172
count = 0
end_time = datetime.now() + timedelta(seconds=10)
while datetime.now() < end_time:
count += 1
print(f'10 second result: {count=:,}')
# 10 second result: count=39,168,578
try this:
import time
import os
n = 0
for x in range(10): #enter your value here
print(n)
time.sleep(1) #to wait a second
os.system('cls') #to clear previous number
#use ('clear') if you are using linux or mac!
n = n + 1

Categories

Resources