Measure the runtime of the program you’re developing using time. (Document)

In programming, many factors influence runtime, and some of them can be unpredictable.

For loops and while loops are often predictable, but I/O operations are not. File operations or memory data processing can significantly impact runtime. When comparing multiple algorithms, precise measurement is essential for making informed decisions.

Most people use it to check the current time or specify a particular time, but for me, it’s the first basic code I write to check the runtime.

I believe it’s a core feature that should be included when developing a product. Monitoring runtime during testing can help identify unexpected issues. Of course, unit tests are fundamental.

Runtime Code

import time

if __name__ == "__main__":
    start_time = time.time()

    # Main Program Code (Your Code or Function)
    time.sleep(1)

    # runtime print
    print(f"""Run Time {(time.time() - start_time)} seconds""")
    print("Run Time %s seconds" % (time.time() - start_time))

    # or decimal point control
    print(f"""Run Time {round((time.time() - start_time),2)} seconds""")
    print("Run Time %.2f seconds" % (time.time() - start_time))
    print("Run Time {:.2f} seconds".format(time.time() - start_time))

Now that I think about it, time.time() represents the time calculated from 00:00:00 on January 1, 1970 (UTC) to the present, but I’m not sure why 1970 was chosen as the base year.

Also, some people find using time.time() redundant and instead declare it upfront as from time import time, using just time(). However, I prefer sticking to the original form.

The reason is that I sometimes create and use functions with short noun-like names, such as time, and keeping the original format helps me distinguish them.

Of course, it doesn’t look as clean, so I usually change it when preparing the code for open source.

Stdout Output

Run Time 1.0002810955047607 seconds
Run Time 1.000603199005127 seconds
Run Time 1.0 seconds
Run Time 1.00 seconds
Run Time 1.00 second

Why isn’t one second of sleep exactly one second? Because it also includes the time it takes for the CPU or memory to process the instructions.

This slight delay can vary depending on your PC’s performance and how busy it is with other tasks.

By Mark

-_-

Leave a Reply

Your email address will not be published. Required fields are marked *