pythoncpupsutil

how to get cpu stats every 15 seconds ? python


see i am using

    import psutil
    d =  psutil.cpu_percent(1.5)
    e =  psutil.cpu_percent(1.5)
    f  =  psutil.cpu_percent(1.5)
    g  =  psutil.cpu_percent(1.5)
    
    val = (d + e +f+g)/4
    print(d , e , f, g)
    print(val)

when I used interval's my import psutil was unreachable


Solution

  • Just use a while loop with 15 seconds time gap using time module.

    So, it should look like this:

    try:
        import psutil, time
        while True:
            d = psutil.cpu_percent(1.5)
            e = psutil.cpu_percent(1.5)
            f = psutil.cpu_percent(1.5)
            g = psutil.cpu_percent(1.5)
            
            val = (d + e + f + g)/4
            print(d, e, f, g)
            print(val)
    
            time.sleep(15)
    except Exception as e:
        print(str(e).capitalize())
    except KeyboardInterrupt:
        print("Finished!")