def get_cpu_usage()

in exec/src/klio_exec/commands/utils/cpu_utils.py [0:0]


def get_cpu_usage(proc, interval=None, stream=None):
    """Measure the cpu % usage at an interval."""
    if not interval:
        interval = 0.1
    if not stream:
        stream = sys.stdout

    line_count = 0
    while True:
        cpu_usage = psutil.cpu_percent()
        timestamp = time.time()
        # Same format as memory_profiler
        stream.write("CPU {:.1f} {:.4f}\n".format(cpu_usage, timestamp))

        time.sleep(interval)
        line_count += 1
        # flush every 50 lines. Make 'tail -f' usable on profile file
        if line_count > 50:
            line_count = 0
            stream.flush()

        if proc.poll() is not None:
            break