Python Timer consuming too much cpu - python

Running below sometimes fails to alert after 9 hours and more over it's consuming 30% or more CPU, when I check in Task Manager. If anyone can tweak this it would be great.
import time
import ctypes
def timer(hours):
seconds = hours * 3600
start = time.time()
time.clock()
elapsed = 0
while elapsed < seconds:
elapsed = time.time() - start
elapsed = elapsed//60
ctypes.windll.user32.MessageBoxA(0,"Done "+str(elapsed) + " Hrs", "Done", 0)
timer(8)

Try this:
import time
import ctypes
def timer(hours):
seconds = hours * 3600
start = time.time()
elapsed = 0
while elapsed < seconds:
# Do something once every minute.
time.sleep(60)
elapsed = time.time() - start
elapsed = elapsed//60
ctypes.windll.user32.MessageBoxA(0,"Done "+str(elapsed) + " Hrs", "Done", 0)
timer(8)
The problem is that you don't sleep() in your loop, so the loop literally just runs many hundreds to thousands or tens of thousands of times per second, eating CPU. The code above will wait 1 minute before repeating the loop.
If you don't need to do anything at all while waiting on the timer, you can avoid the loop entirely and just sleep():
import time
import ctypes
def timer(hours):
time.sleep(hours * 3600)
ctypes.windll.user32.MessageBoxA(0,"Done "+str(hours) + " Hrs", "Done", 0)
timer(8)

Wouldn't this achieve the exact same thing? Since you are not doing anything while looping anyways.
import time
import ctypes
def timer(hours):
start = this.time()
time.sleep(hours * 3600)
ctypes.windll.user32.MessageBoxA(0,"Done "+str(hours) + " Hrs", "Done", 0)

Related

Python mutithreadding, diffrent execution timings

HI I have made a python code to check its multi threading capabilities of the code
here is my code
import os
import time
import threading
count = 0
number_of_itration =10000000
def print_square(num):
# function to print square of given num
begin = time.time()
print(f"T1Begin Time is {begin} Seconds\n")
for i in range(number_of_itration):
format(num * num * num)
end = time.time()
print(f"T1End Time is {end} Seconds\n")
print(f"T1Total runtime of the program is {end - begin} Seconds\n")
def print_square1(num):
# function to print square of given num
begin = time.time()
print(f"T2Begin Time is {begin} Seconds\n")
for i in range(number_of_itration):
format(num * num * num)
end = time.time()
print(f"T2End Time is {end} Seconds\n")
print(f"T2Total runtime of the program is {end - begin} Seconds\n")
def print_square2(num):
# function to print square of given num
begin = time.time()
print(f"T3Begin Time is {begin} Seconds\n")
for i in range(number_of_itration):
format(num * num * num)
end = time.time()
print(f"T3End Time is {end} Seconds\n")
print(f"T3Total runtime of the program is {end - begin} Seconds\n")
def print_square3(num):
# function to print square of given num
begin = time.time()
print(f"T4Begin Time is {begin} Seconds\n")
for i in range(number_of_itration):
format(num * num * num)
end = time.time()
print(f"T4End Time is {end} Seconds\n")
print(f"T4Total runtime of the program is {end - begin} Seconds\n")
def print_square4(num):
# function to print square of given num
begin = time.time()
print(f"T5Begin Time is {begin} Seconds\n")
for i in range(number_of_itration):
format(num * num * num)
end = time.time()
print(f"T5End Time is {end} Seconds\n")
print(f"T5Total runtime of the program is {end - begin} Seconds\n")
def print_square5(num):
# function to print square of given num
begin = time.time()
print(f"T6Begin Time is {begin} Seconds\n")
for i in range(number_of_itration):
format(num * num * num)
end = time.time()
print(f"T6End Time is {end} Seconds\n")
print(f"T6Total runtime of the program is {end - begin} Seconds\n")
t1 = threading.Thread(target=print_square, args=(10,))
t2 = threading.Thread(target=print_square1, args=(10,))
t3 = threading.Thread(target=print_square2, args=(10,))
t4 = threading.Thread(target=print_square3, args=(10,))
t5 = threading.Thread(target=print_square4, args=(10,))
t6 = threading.Thread(target=print_square5, args=(10,))
# starting thread 1
t1.start()
# starting thread 2
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
here Though im calling the same function, with same process, im getting different execution speeds why does it behave like this?
the console print is displayed below
T1Begin Time is 1660808471.2426443 Seconds
T2Begin Time is 1660808471.256599 Seconds
T3Begin Time is 1660808471.256599 Seconds
T4Begin Time is 1660808471.6522112 Seconds
T5Begin Time is 1660808472.0985467 Seconds
T6Begin Time is 1660808472.6798558 Seconds
T2End Time is 1660808478.985982 Seconds
T2Total runtime of the program is 7.7293829917907715 Seconds
T1End Time is 1660808480.8472064 Seconds
T1Total runtime of the program is 9.604562044143677 Seconds
T5End Time is 1660808481.6313431 Seconds
T5Total runtime of the program is 9.532796382904053 Seconds
T3End Time is 1660808482.2941368 Seconds
T6End Time is 1660808482.3155725 Seconds
T6Total runtime of the program is 9.635716676712036 Seconds
T3Total runtime of the program is 11.037537813186646 Seconds
T4End Time is 1660808482.4218156 Seconds
T4Total runtime of the program is 10.769604444503784 Seconds
I would like to know if its expected or not?
I would say that this is unsurprising*. Your program is using one CPU core and you are adding more and more work for the one core as you call .start() on your threads. So you would expect later threads to have some more competition for CPU resources.
* I wouldn't say "expected" purely because performance measurements are hard and lots of unexpected things do crop up.

How to validate time format input?

So basically, i needed to write a program that takes the time of how fast you run a kilometer, and turn it into how long it takes to run a marathon. I got that done, but the problem is that it is supposed to handle if someone inputs the time incorrectly (ex 888 or 5:2555 instead of 8:30)
print "Marathon Time Calculator"
str_pace = raw_input("At what pace do you run a km? (e.g. 5:30): ")
if str_pace.isalpha():
print 'invalid time'
split_pace = str_pace.split(":")
minutes = int(split_pace[0])
seconds = int(split_pace[1])
str_pace = minutes * 60 + seconds
totalTime = str_pace * 42
hours = totalTime // 3600
timeLeft = totalTime % 3600
minutes = timeLeft // 60
seconds = timeLeft % 60
if len(split_pace[1]) >= 3:
print "Too many digits"
else:
print "You should complete a marathon in " + str(hours) + ":" + str(minutes) + ":" + str(seconds)
I have done this in python3
import re
import sys
print("Marathon Time Calculator")
str_pace = input("At what pace do you run a km? (e.g. 5:30): ")
# this is looking for a decimal value of 1 number, then a colon then another decimal value of 1 - 2 numbers
pattern = '\d{1}\:\d{1,2}'
# this is doing the actual check against the pattern for us
match = re.match(pattern, str_pace)
# we now check if there is a match to our pattern
if not match:
print('Invalid Time Input Try Again')
sys.exit
else:
# yes we are entering the value correctly continue the code
split_pace = str_pace.split(":")
minutes = int(split_pace[0])
seconds = int(split_pace[1])
str_pace = minutes * 60 + seconds
totalTime = str_pace * 42
hours = totalTime // 3600
timeLeft = totalTime % 3600
minutes = timeLeft // 60
seconds = timeLeft % 60
print("You should complete a marathon in {}:{}:{}".format(hours, minutes, seconds))

Calculating the amount of time left until completion

I am wondering how to calculate the amount of time it would take to example:
Complete a brute force word list.
I know how to use the time function and measure in time,
but the problem is i need to find out how long it would take in the program itself...
Here is the code i made this yesterday
import itertools, math
import os
Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890") # Add or remove whatevs you think will be in the password you're cracking (example, [symbols])
counter = 1
CharLength = 1
range_num = int(raw_input("Enter range: "))
stopper = range_num + 1
filename = "bruteforce_%r.txt" % (range_num)
f = open(filename, 'a')
#n_1 = len(Alphabet)
#n_2 = n_1 - 1 # <-- total useless peice of garbage that could of been great in vurtual life
#n_3 = '0' * n_2
#n = '1' + n_3
x = range_num
y = len(Alphabet)
amount = math.pow(y, x)
total_items = math.pow(y, x)
for CharLength in range(range_num, stopper):
passwords = (itertools.product(Alphabet, repeat = CharLength))
for i in passwords:
counter += 1
percentage = (counter / total_items) * 100
amount -= 1
i = str(i)
i = i.replace("[", "")
i = i.replace("]", "")
i = i.replace("'", "")
i = i.replace(" ", "")
i = i.replace(",", "")
i = i.replace("(", "")
i = i.replace(")", "")
f.write(i)
f.write('\n')
print "Password: %r\tPercentage: %r/100\tAmount left: %r" % (i, int(percentage), amount)
if i == '0'* range_num:
print "*Done"
f.close()
exit(0)
else:
pass
This is my timer function i managed to make
#import winsound # Comment this out if your using linux
import os
import time
from sys import exit
print "This is the timer\nHit CTRL-C to stop the timer\nOtherwise just let it rip untill the time's up"
hours = int(raw_input('Enter the hours.\n>>> '))
os.system('clear') # Linux
#os.system('cls') # Windows
minutes = int(raw_input('Enter the minutes.\n>>> '))
os.system('clear') # linux
#os.system('cls') # Windows
seconds = int(raw_input('Enter the seconds.\n>>> '))
os.system('clear') # Linux
#os.system('cls') # Windows
stop_time = '%r:%r:%r' % (hours, minutes, seconds)
t_hours = 00
t_minutes = 00
t_seconds = 00
while t_seconds <= 60:
try:
os.system('clear') # Linux
#os.system('cls') # Windows
current_time = '%r:%r:%r' % (t_hours, t_minutes, t_seconds)
print current_time
time.sleep(1)
t_seconds+=1
if current_time == stop_time:
print "// Done"
#winsound.Beep(500,1000)
#winsound.Beep(400,1000)
break
elif t_seconds == 60:
t_minutes+=1
t_seconds=0
elif t_minutes == 60:
t_hours+=1
t_minutes = 00
except KeyboardInterrupt:
print "Stopped at: %r:%r:%r" % (t_hours, t_minutes, t_seconds)
raw_input("Hit enter to continue\nHit CTRL-C to end")
try:
pass
except KeyboardInterrupt:
exit(0)
Now i just cant figure out how to make this again but to calculate how long it will take rather than how long it is taking...
You cannot predict the time a script is going to take.
Firstly because two machines wouldn't run the script in the same time, and secondly, because the execution time on one machine can vary from on take to another.
What you can do, however, is compute the percentage of execution.
You need to figure out, for example, how many iterations your main loop will do, and calculate at each iteration the ratio current iteration count / total number of iterations.
Here is a minimalist example of what you can do:
n = 10000
for i in range(n):
print("Processing file {} ({}%)".format(i, 100*i//n))
process_file(i)
You can take it further and add the time as an additional info:
n = 10000
t0 = time.time()
for i in range(n):
t1 = time.time()
print("Processing file {} ({}%)".format(i, 100*i//n), end="")
process_file(i)
t2 = time.time()
print(" {}s (total: {}s)".format(t2-t1, t2-t0))
The output will look like this:
...
Processing file 2597 (25%) 0.2s (total: 519.4s)
Processing file 2598 (25%) 0.3s (total: 519.7s)
Processing file 2599 (25%) 0.1s (total: 519.8s)
Processing file 2600 (25%)
This is my implementation, which returns time elapsed, time left, and finish time in H:M:S format.
def calcProcessTime(starttime, cur_iter, max_iter):
telapsed = time.time() - starttime
testimated = (telapsed/cur_iter)*(max_iter)
finishtime = starttime + testimated
finishtime = dt.datetime.fromtimestamp(finishtime).strftime("%H:%M:%S") # in time
lefttime = testimated-telapsed # in seconds
return (int(telapsed), int(lefttime), finishtime)
Example:
import time
import datetime as dt
start = time.time()
cur_iter = 0
max_iter = 10
for i in range(max_iter):
time.sleep(5)
cur_iter += 1
prstime = calcProcessTime(start,cur_iter ,max_iter)
print("time elapsed: %s(s), time left: %s(s), estimated finish time: %s"%prstime)
Output:
time elapsed: 5(s), time left: 45(s), estimated finish time: 14:28:18
time elapsed: 10(s), time left: 40(s), estimated finish time: 14:28:18
time elapsed: 15(s), time left: 35(s), estimated finish time: 14:28:18
....
You will never ever be able to know exactly how long it is going to take to finish. The best you can do is calculate was percentage of the work you have finished and how long that has taken you and then project that out.
For example if you are doing some work on the range of numbers from 1 to 100 you could do something such as
start_time = get the current time
for i in range(1, 101):
# Do some work
current_time = get the current time
elapsed_time = current_time - start_time
time_left = 100 * elapsed_time / i - elapsed_time
print(time_left)
Please understand that the above is largely pseudo-code
The following function will calculate the remaining time:
last_times = []
def get_remaining_time(i, total, time):
last_times.append(time)
len_last_t = len(last_times)
if len_last_t > 5:
last_times.pop(0)
mean_t = sum(last_times) // len_last_t
remain_s_tot = mean_t * (total - i + 1)
remain_m = remain_s_tot // 60
remain_s = remain_s_tot % 60
return f"{remain_m}m{remain_s}s"
The parameters are:
i : The current iteration
total : the total number of iterations
time : the duration of the last iteration
It uses the average time taken by the last 5 iterations to calculate the remaining time. You can the use it in your code as follows:
last_t = 0
iterations = range(1,1000)
for i in iterations:
t = time.time()
# Do your task here
last_t = time.time() - t
get_remaining_time(i, len(iterations), last_t)

fps - how to divide count by time function to determine fps

I have a counter working that counts every frame. what I want to do is divide this by time to determine the FPS of my program. But I'm not sure how to perform operations on timing functions within python.
I've tried initializing time as
fps_time = time.time
fps_time = float(time.time)
fps_time = np.float(time.time)
fps_time = time()
Then for calculating the fps,
FPS = (counter / fps_time)
FPS = float(counter / fps_time)
FPS = float(counter (fps_time))
But errors I'm getting are object is not callable or unsupported operand for /: 'int' and 'buildin functions'
thanks in advance for the help!
Here is a very simple way to print your program's frame rate at each frame (no counter needed) :
import time
while True:
start_time = time.time() # start time of the loop
########################
# your fancy code here #
########################
print("FPS: ", 1.0 / (time.time() - start_time)) # FPS = 1 / time to process loop
If you want the average frame rate over x seconds, you can do like so (counter needed) :
import time
start_time = time.time()
x = 1 # displays the frame rate every 1 second
counter = 0
while True:
########################
# your fancy code here #
########################
counter+=1
if (time.time() - start_time) > x :
print("FPS: ", counter / (time.time() - start_time))
counter = 0
start_time = time.time()
Hope it helps!
Works like a charm
import time
import collections
class FPS:
def __init__(self,avarageof=50):
self.frametimestamps = collections.deque(maxlen=avarageof)
def __call__(self):
self.frametimestamps.append(time.time())
if(len(self.frametimestamps) > 1):
return len(self.frametimestamps)/(self.frametimestamps[-1]-self.frametimestamps[0])
else:
return 0.0
fps = FPS()
for i in range(100):
time.sleep(0.1)
print(fps())
Make sure fps is called once per frame
You might want to do something in this taste:
def program():
start_time = time.time() #record start time of program
frame_counter = 0
# random logic
for i in range(0, 100):
for j in range(0, 100):
# do stuff that renders a new frame
frame_counter += 1 # count frame
end_time = time.time() #record end time of program
fps = frame_counter / float(end_time - start_time)
Of course you don't have to wait the end of the program to compute end_time and fps, you can do it every now and then to report the FPS as the program runs. Re-initing start_time after reporting the current FPS estimation could also help with reporting a more precise FPS estimation.
This sample code of finding FPS. I have used it for pre, inference, and postprocessing. Hope it helps!
import time
...
dt, tt, num_im = [0.0, 0.0, 0.0], 0.0, 0
for image in images:
num_im += 1
t1 = time.time()
# task1....
t2 = time.time()
dt[0] += t2 - t1
# task2...
t3 = time.time()
dt[1] += t3 - t2
# task3...
dt[2] += time.time() - t3
tt += time.time() - t1
t = tuple(x / num_im * 1E3 for x in dt)
print(f'task1 {t[0]:.2f}ms, task2 {t[1]:.2f}ms, task3 {t[2]:.2f}ms, FPS {num_im / tt:.2f}')
from time import sleep,time
fps = 0
fps_count = 0
start_time = time()
while True:
if (time()-start_time) > 1:
fps = fps_count
fps_count = 1
start_time = time()
else:
fps_count += 1
print("FPS:",fps)
FPS = the number of cycles running per second

Python Time Math

I want to write a program that allows the user to enter in a start time hour, end time hour, and number of divisions.
So they might enter 9, 10, and 4 which should mean a start time of 9:00AM, end of 10:00AM and to split the range 4 times, resulting in an output of 9:00, 9:15, 9:30, 9:45.
I've tried using the time module and datetime, but cannot get the addition of time to work. I do not care about date.
I can calculate the time split, but the actual addition to the start time is evading me.
I have a hodge-podge of code, and the following is mostly me experimenting trying to figure out how to make this work. I've tried adding the minutes, tried converting to seconds, delved into datetime, tried the time module, but can't seem to get it to work. There are plenty of examples of how to "add 15 minutes to now" but the issue is I don't want to start at the "now", but rather let the user decide start time.
Thank you.
time_start = "9"
time_end = "10"
time_split = "4"
if len(time_start) == 1:
time_start = "0" + str(time_start) + ":00"
else:
time_start = str(time_start) + ":00"
if len(time_end) == 1:
time_end = "0" + str(time_end) + ":00"
else:
time_end = str(time_end) + ":00"
print time_start
print time_end
s1 = time_start + ':00'
s2 = time_end + ':00'
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
divided = tdelta / int(time_split)
print tdelta
print divided
s3 = str(divided)
print "s1 time start: " + str(s1)
print "s2 time end: " + str(s2)
print "s3 time divided: " + str(s3)
ftr = [3600,60,1]
add_seconds = sum([a*b for a,b in zip(ftr, map(int,s3.split(':')))])
print "s3 time divided seconds: " + str(add_seconds)
print "time delta: " + str(tdelta)
EDIT: I did a small bit of research and found a much better solution that elegantly handles resolution to the millisecond. Please implement this code instead (though I will save the old code for posterity)
import datetime
start_time = 9 # per user input
end_time = 10 # per user input
divisions = 7 # per user input
total_time = end_time - start_time
start_time = datetime.datetime.combine(datetime.date.today(),datetime.time(start_time))
end_time = start_time + datetime.timedelta(hours=total_time)
increment = total_time*3600000//divisions # resolution in ms
times = [(start_time+datetime.timedelta(milliseconds=increment*i)).time()
for i in range(divisions)]
from pprint import pprint
pprint(list(map(str,times)))
# ['09:00:00',
# '09:08:34.285000',
# '09:17:08.570000',
# '09:25:42.855000',
# '09:34:17.140000',
# '09:42:51.425000',
# '09:51:25.710000']
If I were you, I'd do my math as raw minutes and use datetime.time only to save the results as something more portable.
Try this:
import datetime
start_time = 9 # per user input
end_time = 10 # per user input
divisions = 4 # per user input
total_minutes = (end_time-start_time)*60
increment = total_minutes // divisions
minutes = [start_time*60]
while minutes[-1] < end_time*60:
# < end_time*60 - increment to exclude end_time from result
minutes.append(minutes[-1] + increment)
times = [datetime.time(c//60,c%60) for c in minutes]
# [09:00:00,
# 09:15:00,
# 09:30:00,
# 09:45:00,
# 10:00:00]

Categories

Resources