import time
l=[]
start = time.perf_counter()
for i in range(20000000):
l.append(i)
end = time.perf_counter()
print(end-start)
Yields 2.7262994
I'm not sure how to read that. If 2 is seconds, then how is there 7262994 milliseconds? Does anyone know how to convert fractional seconds to milliseconds?
There are 1000 milliseconds in one second, so just multiply the number of seconds by 1000:
>>> seconds = 2.7262994
>>> milliseconds = seconds * 1000
>>> milliseconds
2726.2994
If you want a whole number of milliseconds, then round it and convert to an int:
>>> int(round(milliseconds))
2726
Reading the docs time.perf_counter() returns fractional seconds. Based on that we have following case:
import time
start = time.perf_counter()
time.sleep(1) # sleeping 1 second
end = time.perf_counter()
print(f"Elapsed time in seconds: {end-start}")
time_elapsed_ms = (end-start)*1000
print(f"Elapsed time in miliseconds: {time_elapsed_ms}")
Output is:
Elapsed time in seconds: 1.0009973929991247
Elapsed time in miliseconds: 1000.9973929991247
So 1 s = 1000 ms
If you want your result in integer form you can round it and then cast to int int(round((end-start)*1000)):
import time
start = time.perf_counter()
time.sleep(0.34) # sleeping 340 mili seconds
end = time.perf_counter()
print(f"Elapsed time in seconds: {end-start}")
time_elapsed_ms = int(round((end-start)*1000))
print(f"Elapsed time in miliseconds: {time_elapsed_ms}")
Elapsed time in seconds: 0.3404383749948465
Elapsed time in miliseconds: 340
.perf_counter() returns a float value (seconds) so if you cast it to int * 1000 you would have your milliseconds.
Related
I have written this code where I want that code to run exactly at the minute. However, each iteration take few milliseconds and this causes a small delay in my program. Is there a way to where I can subtract these milliseconds just like the way I have subtracted seconds.
import pandas as pd
import datetime as dt
import time
while True:
now = dt.datetime.now()
current_time = now.strftime('%Y-%m-%d %H:%M:%S')
seconds = int(current_time[-2:])
sleep_sec = 60 - seconds
time.sleep(sleep_sec)
print(dt.datetime.now())
This is the output:
As you can see from the output that with each iteration few milliseconds are added to the time. What I want is to print the exact minute where milliseconds is also zero.
using time.time() instead of time.sleep()
import time
import datetime as dt
start_time = time.time()
while True:
if time.time() - start_time > 60:
# if 60 seconds pass do something
print(dt.datetime.now())
start_time = time.time()
print("60 seconds passed")
output:
2021-12-24 12:48:30.542806
60 seconds passed
2021-12-24 12:49:30.543792
60 seconds passed
2021-12-24 12:50:30.544508
60 seconds passed
2021-12-24 12:51:30.544826
60 seconds passed
2021-12-24 12:52:30.545028
60 seconds passed
2021-12-24 12:53:30.545661
60 seconds passed
2021-12-24 12:54:30.546452
60 seconds passed
there's still offset, but it's less significant than in your output
time.sleep accepts float if you want to sleep for fractions of seconds. That being said I would not expect python to be able to do exact milisecond precision (there is just way too much happening in your system usually for this level of precision).
With threading the code is fast and executes exactly at the start of the minute.
def create_candle():
candle_timeframe = 60 # seconds
current_sec = dt.datetime.now().second
sleep_sec = candle_timeframe - current_sec
print(dt.datetime.now())
threading.Timer(sleep_sec, create_candle).start()
candle_timeframe = 60 # seconds
current_sec = dt.datetime.now().second
sleep_sec = candle_timeframe - current_sec
threading.Timer(sleep_sec, create_candle).start()
I would like to measure the execution time of some piece of code in days, hours, minutes and seconds.
This is what I have so far:
import time
start_time = time.time()
# some code
elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time))
print(f"Took: {elapsed}")
The problem is that if the code that I am measuring takes longer than 24h, the time displayed overflows and starts from zero again. I would like something like this:
# Example: 12 hours and 34 minutes should be printed as
> Took: 12:34:00
# Example: 26 hours and 3 minutes should be printed as
> Took: 1:02:03:00
You could use datetime:
from datetime import datetime as dt
start = dt.fromtimestamp(1588432670)
end = dt.now()
elapsed=end-start
print("Took: %02d:%02d:%02d:%02d" % (elapsed.days, elapsed.seconds // 3600, elapsed.seconds // 60 % 60, elapsed.seconds % 60))
Output:
Took: 33:00:21:49
The result of time.gmtime(time.time() - start_time) is not what you seem to think it is. Instead of being a duration of time it is a point in time. Let me explain.
The result of time.time() is the number of seconds since January 1, 1970, 00:00:00 (UTC) at the time of calling. Therefore, the statement time.time() - start_time will produce the number of seconds between the two calls. So far so good. However, the time.gmtime function is interpreting this duration as the number of seconds since January 1, 1970, 00:00:00 (UTC) and formatting the time accordingly. What you are seeing then is the time portion of the date January 1, 1970, 12:34:00 (UTC).
I suggest you either use the datetime.timedelta object and format using that, or as others have suggested, output the duration in seconds or milliseconds.
If you want to format this number yourself, you could use something like this:
def format_duration(duration):
mapping = [
('s', 60),
('m', 60),
('h', 24),
]
duration = int(duration)
result = []
for symbol, max_amount in mapping:
amount = duration % max_amount
result.append(f'{amount}{symbol}')
duration //= max_amount
if duration == 0:
break
if duration:
result.append(f'{duration}d')
return ' '.join(reversed(result))
You should try this:
import time
start_time = time.time()
...
elapsed_time = time.time() - start_time
days = 0
if elapsed_time >= 86400:
days = int(elapsed_time / 86400)
elapsed = time.strftime("%H:%M:%S", time.gmtime(time.time() - start_time))
if days == 0:
print(f"Took: {elapsed}")
else:
print(f"Took: {days}:{eplased}")
Time types can only include hours and less units. You should use datetime instead of time as follows:
from datetime import datetime
start_time = datetime.now()
# some code
elapsed = datetime.now() - start_time)
print(f"Took: {elapsed}")
Example usage of Datetime:
from datetime import datetime
d1 = datetime(2013,9,1,5,5,4)
d2 = datetime(2013,1,13,3,2,1)
result1 = d1-d2
print ('{} between {} and {}'.format(result1, d1, d2))
This produces following output:
231 days, 2:03:03 between 2013-09-01 05:05:04 and 2013-01-13 03:02:01
Try using timeit:
import timeit
timeit.timeit(<callable function>, number = 100)
Here timeit will call callable function number times and give you the average runtime.
How would I go about converting a float like 3.65 into 4 mins 5 seconds.
I have tried using:
print(datetime.datetime.strptime('3.35','%M%-S'))
However, I get this back:
ValueError: '-' is a bad directive in format '%-M:%-S'
Take a look at the following script, you can figure out how to make it work for days years, etc, this only works if we assume the format is "hours.minutes"
import datetime
# Assuming the 3 represents the hours and the 0.65 the minutes
number = 3.65
# First, we need to split the numbero into its whole decimal part
# and its decimal part
whole_decimal_part = hours = int(number) # 3
decimal_part = number % whole_decimal_part # 0.6499999
# Now, we need to know how many extra hours are in the decimal part
extra_hours = round((decimal_part * 100) / 60) # 1
minutes = round((decimal_part * 100) % 60) # 5
hours += extra_hours # 4
time_str = "%(hours)s:%(minutes)s" % {
"hours": hours,
"minutes": minutes
} # 4:5
final_time = datetime.datetime.strptime(time_str, "%H:%M").time()
print(final_time) # 04:05:00
First, you should complain to whoever is giving you time data expressed like that.
If you need to process minutes and seconds as a standalone value, then the datetime object may not your best choice either.
If you still need to convert "3.65" into a datetime object corresponding to "4-05" you could adjust it to be a valid time representation before passing it to strptime()
m,s = map(int,"3.65".split("."))
m,s = (m+s)//60,s%60
dt = datetime.datetime.strptime(f"{m}-{s}","%M%-S")
Split your time into minute and seconds
If seconds is 60 or more, then add extra minutes (//) ; second is the modulo (%)
t="3.65"
m, s = [int(i) for i in t.split('.')]
if s >= 60:
m += s//60
s = s % 60
print(f'{m} mins {s} seconds') # -> 4 mins 5 seconds
while 65 seconds cannot be parsed correctly so you have to manipulate by yourself to clean the data first before parsing.
NOTE: assuming seconds is not a very very big number which can make minutes>60
import datetime
time= '3.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
minute_offset, seconds = divmod(seconds, 60);
minute = int(split_time[0]) + minute_offset
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S')) #1900-01-01 00:04:05
You can alternatively use .time() on datetime object to extract the time
print(datetime.datetime.strptime('{}.{}'.format(minute,seconds),'%M.%S').time()) #00:04:05
A much cleaner and safer solution is (to consider hour as well). Convert everything into seconds and then convert back to hours, minutes, seconds
def convert(seconds):
min, sec = divmod(seconds, 60)
hour, min = divmod(min, 60)
return "%d:%02d:%02d" % (hour, min, sec)
time='59.65'
split_time = time.split(".")
minute =int(split_time[0])
seconds = int(split_time[1])
new_seconds = minute*60 +65
datetime.datetime.strptime(convert(new_seconds),'%H:%M:%S').time()
I am able to compute elapsed time, but I dont know how to print results in ms (i need integer, like this: 20ms, 30ms..)
import datetime
start_time = datetime.datetime.now()
print 'some long procedure'
elapsed = datetime.datetime.now() - start_time
print int(elapsed).strftime("%s")) * 1000 #<------- not working
The total_seconds method of datetime.timedelta objects returns the number of seconds, as a float, so it includes the fractions of second - see timedelta.total_seconds.
So, you just have to multiply it by 1000 to convert it to milliseconds, and keep the integer part.
import datetime
start_time = datetime.datetime.now()
print 'some long procedure'
elapsed = datetime.datetime.now() - start_time
print(int(elapsed.total_seconds()*1000))
I need express my time in Hours and minutes. This is what I have:
0.0425 hours
~153 seconds, How can I show this as 0 Hours 2 minutos 33 seconds?
Here is one way.
time = '0.0425 hours'
# Extract time from string
time = time.split()[0]
# Convert time to a number of hours, then a number of seconds
time = float(time)
time = int(time * 3600)
# Compute the constituent elements of the time
hours = time // 3600
minutes = (time // 60) % 60
seconds = time % 60
# Print the result
print '{hours} Hours {minutes} minutos {seconds} seconds'.format(
hours=hours, minutes=minutes, seconds=seconds)
import time
import re
secs = int(re.sub('\D', '','~153'))
print '%d hours %d minutos %s seconds'%(time.gmtime(secs)[3:6])