Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Resource Usage Information ใน Python (โมดูล resource)

โมดูล resource ใช้วัดและควบคุม Resource Usage ของ Process ใน UNIX (CPU Time, Memory, File Descriptors, etc.)

import resource


Resource Limits (การจำกัดทรัพยากร)

มี 2 ระดับ:

  • Soft Limit: ขีดจำกัดปัจจุบัน แก้ไขได้ แต่ไม่เกิน Hard Limit
  • Hard Limit: ขีดจำกัดสูงสุด ลดได้ แต่เพิ่มไม่ได้ (ต้อง Root)

เมธอดหลัก

  • getrlimit(resource) - คืน (soft, hard)
  • setrlimit(resource, (soft, hard)) - ตั้งค่า Limit
  • prlimit(pid, resource[, limits]) - Get/Set พร้อมกัน (PID=0 = Current Process)

Resource Constants สำคัญ

Constantคำอธิบาย
RLIMIT_CPUCPU Time สูงสุด (วินาที) - เกินได้ Signal SIGXCPU
RLIMIT_DATAHeap Size สูงสุด
RLIMIT_STACKStack Size สูงสุด
RLIMIT_NOFILEOpen File Descriptors สูงสุด
RLIMIT_MEMLOCKLocked Memory สูงสุด
RLIMIT_NPROCProcess สูงสุดต่อ User
RLIMIT_ASAddress Space สูงสุด (Virtual Memory)
RLIM_INFINITYไม่จำกัด

Resource Usage (การใช้ทรัพยากร)

resource.getrusage(who)

คืน Object มีฟิลด์:

  • ru_utime - User CPU Time
  • ru_stime - System CPU Time
  • ru_maxrss - Max Resident Set Size (KB)
  • ru_minflt/ru_majflt - Page Faults
  • ru_nswap - Swap Count
  • ru_inblock/ru_oublock - Block I/O
  • ru_nvcsw/ru_nivcsw - Context Switches

Who Constants

Constantความหมาย
RUSAGE_SELFProcess ปัจจุบัน (รวม Threads)
RUSAGE_CHILDRENChild Processes
RUSAGE_BOTHSelf + Children (ไม่รองรับทุก OS)
RUSAGE_THREADCurrent Thread เท่านั้น (Linux 2.6.26+)

โค้ดตัวอย่าง

import resource

# ดู Resource Usage
usage = resource.getrusage(resource.RUSAGE_SELF)
print(usage)
print('Page Size:', resource.getpagesize())

# จำกัด CPU Time 1 วินาที (Soft), 2 วินาที (Hard)
resource.setrlimit(resource.RLIMIT_CPU, (1, 2))
print('CPU Limits:', resource.getrlimit(resource.RLIMIT_CPU))

# Loop หนักเพื่อทดสอบ
for a in range(1000):
    for b in range(1000):
        for c in range(1000):
    pass

ผลลัพธ์

resource.struct_rusage(ru_utime=0.035801, ru_stime=0.01074, ru_maxrss=9356, ...)
Page Size: 4096
CPU Limits: (1, 2)
CPU time limit exceeded (core dumped)

การประยุกต์ใช้

  • ป้องกัน Process รันนานเกินไป (Runaway Process)
  • จำกัด Memory ป้องกัน OOM Killer
  • Monitoring/Profiling Performance
  • Sandboxing Untrusted Code