Jump to content

Displaying System info in Python


zak100

Recommended Posts

33 minutes ago, zak100 said:

Thanks for your interest in solving my problem. Through your guidance, I am able to print cpu_percent. Of course I have to use 10,000 integer numbers. Now the problem is w.r.t printing of cpu_percent twice as I discussed in post#24. 

 

Please guide me why the code is printing cpu_percent() message twice.

Try sorting 5000 numbers or use a CPU that is twice as fast? 

To be honest at this time, given the following question:

1 hour ago, zak100 said:

It might be possible that this line:


print("CPU usage:" + str(psutil.Process(pid).cpu_percent(interval=1)))

 

is being executed by both the main thread and the new thread. Please guide me.

I think it is better to not use separate threads, it looks like you need something more basic and learn from there.

Questions:
-Is your requirement to measure CPU percentage every second? (interval=1)
-Are you required to use psutil? Or is any other method OK?

 

Link to comment
Share on other sites

Here is a simple hack, no threading, no blocking calls. 

import time

# get time before doing work
process_time=time.process_time()
real_time=time.time()

# meaningless work to vaste CPU:
for v in range(1000000):i=v/3.0 

# print process time used divided by time passed:
print("{:0.2f}".format(100*(time.process_time()-process_time)/(time.time()-real_time))+"% CPU usage")

Typical output:

49.19% CPU usage

Maybe more useful an inline with the current level of understanding. 

 

Documentation for time.process_time() and time.time(): https://docs.python.org/3/library/time.html

Edited by Ghideon
Link to comment
Share on other sites

Hi,

Thanks for your reply.

I am thinking of using the 2nd approach also. But right now I want to correct the cpu usage message problem with the first approach. Please guide me. I want to understand what is my error?

 

I ran the code for 5000 values but still I got multiple values for cpu usages:

Quote

start thread
CPU usage:100.4
CPU usage:101.4

 

Though at the end it printed me the single value:

Quote

(4998, 99997)
(4999, 99998)
CPU usage:22.3
all done
memory usage=  15884288
disk usage=  sdiskusage(total=982900588544, used=141444521984, free=791455981568, percent=15.2)
virtual mem=  11002109952
rss=  15884288

 

Thanks for your cooperation.

 

Zulfi.

Link to comment
Share on other sites

Hi,

My code for selection sort, It prints 3 CPU usage statements: 2 after display random numbers and one after sorting.

import random
import psutil
import os
import threading

class SSSort:
    arr = []  # class var access by className.arr

    def __init__(self, n):
        self.n = n

    def generate1000_5digit_RandomNum(self):
        for i in range(self.n):
            num = random.randint(10000, 99999)
            SSSort.arr.append(num)

        for j in range(self.n):
            print("random {0}".format(SSSort.arr[j]))

    def cpu_util_info(self):#make sure different than posted
        k= self.n
        arr2 = SSSort.arr[:]
        def find_the_min_element(k, i, arr2):
           min = i
           for j in range(i+1, k):
              if (arr2[j] < arr2[min]):
                 min = j
           return min

        def selectionSort(k, arr2):
            for i in range(self.n):
                min = find_the_min_element(k, i, arr2)
                # swap min and ith element of array
                temp = arr2[min]
                arr2[min]= arr2[i]
                arr2[i] =temp

            for i in enumerate(arr2):
                print(i)


        pid = os.getpid()  # current process
        print("start thread")
        psutil.Process(pid).cpu_percent(interval=0)
        th = threading.Thread(target=selectionSort, args=(k, arr2))
        th.start()
        while th.is_alive():
            print("CPU usage:" + str(psutil.Process(pid).cpu_percent(interval=1)))
        print("all done")


    
    def main(self):
        self.generate1000_5digit_RandomNum()
        self.cpu_util_info()
        print("memory usage= ", psutil.Process(os.getpid()).memory_info()[0])
        print("disk usage= ", psutil.disk_usage('/'))
        print("virtual mem= ", psutil.virtual_memory().available)
        print("rss= ", psutil.Process(os.getpid()).memory_info().rss)


if __name__ == "__main__":
    objSSSort = SSSort(10000)
    objSSSort.main()

The output is:

Quote

random 45227
start thread
CPU usage:99.3
(0, 10013)
(1, 10059)
(2, 10062)

:

:

:

(4995, 99923)
(4996, 99940)
(4997, 99949)
(4998, 99969)
(4999, 99985)
CPU usage:1.0
all done
memory usage=  15691776
disk usage=  sdiskusage(total=982900588544, used=141446012928, free=791454490624, percent=15.2)
virtual mem=  11311255552
rss=  15691776

 

Note for 5000, I am getting 2 spu percentages one after random and one after sorting. The above is for 10000 numbers.

 

Thanks for your cooperation.

 

Zulfi.

Link to comment
Share on other sites

5 hours ago, zak100 said:

But right now I want to correct the cpu usage message problem with the first approach. Please guide me. I want to understand what is my error?

 

Your error is that you do not state your requirements,  the implementation and the output may then not match your expectations.

  • You have asked for the program to print something else than 0.0. Fixed: The program does so by executing sorting to use up CPU resources so that measurement is > 0.0.
  • Using psutil and Interval=1 is, I believe, your requirement according to my best guess given the information provided. Fixed: using a separate thread to avoid the blocking call. 

Result is that your current program measures and print the CPU usage once every second (as required) for a task that takes more than one second to complete on your CPU. Result is that you have more than one message printed. 

There are many ways to change the code to get some alternative output, for instance an output of one single CPU reading. What have you tried? Any ideas? 


Hint: You could store the measurements instead of printing each of them. Then calculate and print a grand total when sorting is done. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.