Arthur Grigoryan
Arthur Grigoryan

Reputation: 467

How to convert fractional seconds to milliseconds?

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?

Upvotes: 0

Views: 10207

Answers (3)

karlosos
karlosos

Reputation: 1184

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

Upvotes: 1

kaya3
kaya3

Reputation: 51152

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

Upvotes: 2

Thailo
Thailo

Reputation: 1424

.perf_counter() returns a float value (seconds) so if you cast it to int * 1000 you would have your milliseconds.

Upvotes: 0

Related Questions