본문 바로가기
  • Java - developer
  • code start
  • code
python

python psutil 을 이용한 성능 측정

by Rhi_co 2023. 1. 8.

파이썬을 이용하여 PC에 대한 정보를 얻기 위해서 찾다보니 psutil 이란 라이브러리를 이용하여 여러가지 PC 정보를 가져올 수 있다는것을 알게 되어 사용하게 되었습니다.

측정한 정보는 cpu, 메모리, 저장공간, 네트워크 사용량 등이 있습니다. 추가적으로 필요한 정보를 얻고 싶으시다면 psutil 검색을 통해서 더욱 자세히 정보를 얻을 수 있으니 찾아보셔도 좋을 것 같습니다.

 

코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import psutil
import time
 
def get_size_bytes(bytes):
    for unit in ['''K''M''G''T''P']:
        if bytes < 1024:
            return f"{bytes:.2f}{unit}B"
        bytes /= 1024
 
def get_size_bps(bytes):
 
    bytes *=8
    for unit in ['''K''M''G''T''P']:
        if bytes < 1024:
            return f"{bytes:.2f}{unit}bps"
        bytes /= 1024
 
def work() :
    UPDATE_DELAY = 1
    io = psutil.net_io_counters()
    bytes_sent, bytes_recv = io.bytes_sent, io.bytes_recv
    while True:
        time.sleep(UPDATE_DELAY)
        # CPU
        cpu_ = psutil.cpu_percent(interval=None, percpu=False)
            
        # Memory
        memory_ = psutil.virtual_memory()
 
         # disk memory
        disk_c = 'C://'
        disk_ = psutil.disk_usage(disk_c); 
 
         # network
        io_2 = psutil.net_io_counters()
        us, ds = io_2.bytes_sent - bytes_sent, io_2.bytes_recv - bytes_recv
 
        dict_example = {
                        'time' : time.strftime('%H%M%S', time.localtime(time.time())),
                        'cpu' :f"{cpu_}",
                        'memory_used' :f"{get_size_bytes(memory_.used)}",
                        'memory_total' :f"{get_size_bytes(memory_.total)}",
                        'memory_percent' :f"{memory_.percent}",
                        'disk_used' :f"{get_size_bytes(disk_.used)}",
                        'disk_total' :f"{get_size_bytes(disk_.total)}",
                        'disk_percent' : f"{disk_.percent}",          
                       'network_upload_speed': f"{get_size_bps(us)}",
                    'network_download_speed': f"{get_size_bps(ds)}"
                        }
        print(dict_example)
        bytes_sent, bytes_recv = io_2.bytes_sent, io_2.bytes_recv
if __name__ == "__main__":
    work();
 
 
    
cs

 

참고

https://morioh.com/p/d4e97d9b03de

 

Python으로 네트워크 트래픽 모니터를 만드는 방법

psutil 및 Scapy 라이브러리를 결합하여 Python에서 네트워크 인터페이스 및 프로세스당 네트워크 트래픽 모니터를 만드는 방법을 배웁니다.

morioh.com

 

'python' 카테고리의 다른 글

python bytes to GB,MB,KB or G,M,Kbps 단위로 변환 함수  (0) 2023.01.07
python 북마크 크롤링  (0) 2020.12.22

댓글