Timedelta only shows 2 digits in some cases

Question:

I got the following lines of code:

from datetime import datetime

def my_function():
    start_time = datetime.now()

    # Do something

    end_time = datetime.now()

    return (end_time - start_time).microseconds

print(my_function)

If the function executes "slow enough", I manage to get output like 906 or 1021. But sometimes, if I execute the function, I simply got the result 0, no matter if I use other methods as well, like:

    return (end_time - start_time).total_seconds()

or:

    return (end_time - start_time) * 1000

I sometimes still get just 0 as output. Can anyone tell me how I’m able to retrieve the time delta in any case?

Any help would be apprechiated. Kind regards.

Asked By: Aiden3301

||

Answers:

Depending on what you do you can have a look at the time module and look at the following functions time.time(), time.perf_counter() or even time.perf_counter_ns()

For instance

import time

def my_function():
    start_time = time.perf_counter_ns()

    # Do something

    end_time = time.perf_counter_ns()

    return return (end_time - start_time) / 1_000_000 # if you want result in ms

my_function()
Answered By: WArnold