[Python] use of time.perf_counter_ns() in a loop seems to overburden CPU

Discussão em 'Python' iniciado por Stack, Junho 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am using a code which runs some actions infinitely, as well as performing additional actions that should be performed at a lower frequency - specified in milliseconds interval. Since I need a function whose resolution scales to milliseconds, I found that time.perf_counter_ns() can fit:

    import time

    last_time_ns = time.perf_counter_ns()

    while True:
    # do different stuff

    current_time_ns = time.perf_counter_ns()
    elapsed_time_ms = (current_time_ns - last_time_ns) / 1_000_000

    if elapsed_time_ms > 500:
    print("do something every 500 ms")
    last_time_ns = current_time_ns


    But this seems to really overburden my CPU and cause the fan to be pretty loud (compared to when this program is turned off). My PC is quite strong and can run other heavy programs with ease. I did narrow the program to remove any suspect actions so I am pretty sure it is the perf function that causes it.

    So is time.perf_counter_ns() that heavy a function on resources? Are there alternatives which are light and can be used for my purpose?

    Continue reading...

Compartilhe esta Página