Search code examples
pythonpython-3.xtimeroundingdecimal-point

Calculate RTT with 3 decimal places in Python 3


I have a simple UDP client–server program and I get the time in ms of sending a packet and the time in ms of receiving the packet like this:

send_time_ms = int(round(time.time() * 1000))
# sending the packet
# ...
# receiving the packet
recv_time_ms = int(round(time.time() * 1000))

For example, I get 1430645866889 and 1430645866898. I would like to then find the difference between these two values and round it to a value with 3 decimal places, like 0.291 and so on. I tried subtracting them, but it gave me 9 or 10.0 in float. I must be doing this wrong.

Could you please help me find a way to edit the time.time() code so I can do this?


Solution

  • Use the second argument of round which indicates the number of numbers after the decimal:

    send_time_ms = time.time()
    ...
    recv_time_ms = time.time()
    rtt_in_ms = round(recv_time_ms - send_time_ms, 3)