How can I make countdown time? - python

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

Related

Time before full counter with percent python

how to calculate based on timestamp and get the progress before the max full value?
def full_energy():
time_now = 1666650096 #changes every update
time_end = 1666679529
max_energy = 50
diff = datetime.utcfromtimestamp(time_now) - datetime.utcfromtimestamp(time_end)
secs = diff.total_seconds()
???
# expected output
# x/y (z)
# 25/50 (50%)
how to get the value of x and z based on this sample?
Something like this will work. You need to provide the start time to compute percent completed. Not sure how you want the display to function:
from datetime import datetime, timedelta
import time
def full_energy(start, now, end):
max_energy = 50
percent = (now - start) / (end - start)
current_energy = max_energy * percent
# In a typical text console this will overwrite the same line
print(f'\r{current_energy:.0f}/{max_energy} ({percent:.0%})', end='', flush=True)
start = datetime.now()
end = start + timedelta(seconds=10)
while (now := datetime.now()) <= end:
time.sleep(.2)
full_energy(start, now, end)

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)

Time measurement - function with an input inside

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?

Timing a Python program using time.clock() vs. time.time() [duplicate]

This question already has answers here:
Python's time.clock() vs. time.time() accuracy?
(16 answers)
Closed 6 years ago.
I am new to Python programming. I started working on Project Euler this morning and I wanted to find out how long it takes to execute my solution. I have searched online for a solution to my
import time
class Solution(object):
def fibonacci(self,limit):
sum = 0
current = 1
next = 2
while(current <= limit):
if current % 2==0:
sum += current
current, next = next, current + next
return str(sum)
if __name__ == "__main__":
start = time.clock()
solution = Solution().fibonacci(4000000)
elapsed = time.clock()-start
print("Solution: %s"%(solution))
print("Time: %s seconds"%(elapsed))
Output:
Solution: 4613732
Time: 2.006085436846098e-05 seconds
import time
class Solution(object):
def fibonacci(self,limit):
sum = 0
current = 1
next = 2
while(current <= limit):
if current % 2==0:
sum += current
current, next = next, current + next
return str(sum)
if __name__ == "__main__":
start = time.time()
solution = Solution().fibonacci(4000000)
elapsed = time.time()-start
print("Solution: %s"%(solution))
print("Time: %s seconds"%(elapsed))
Output:
Solution: 4613732
Time: 0.0 seconds
My question is
Is the time calculated above correct?
What is the difference between time.time() vs time.clock(). If I use time.time() I get 0.0 as time.
In the Python time module, time.clock() measures the time since the first call of the function in seconds, and time.time() measures the time since January 1st, 1970, in seconds.
time.clock() is generally more precise, so using this is what I recommend. This is the reason why you have the tiny result in the first example, rounded down to zero in the second example.

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().

Categories

Resources