forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulate_memory_cpu.py
81 lines (62 loc) · 1.63 KB
/
simulate_memory_cpu.py
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#! /user/bin/env python
# -*- encoding: utf-8 -*-
"""
Simulate cpu、 memory usage
"""
import sys
import re
import time
from multiprocessing import Process, cpu_count
def print_help():
print('Usage: ')
print(' python cpu_memory_simulator.py m 1GB')
print(' python cpu_memory_simulator.py c 1')
print(' python cpu_memory_simulator.py mc 1GB 2')
# memory usage
def mem():
pattern = re.compile('^(\d*)([M|G]B)$')
size = sys.argv[2].upper()
match = pattern.match(size)
if match:
num = int(match.group(1))
unit = match.group(2)
if unit == 'MB':
s = ' ' * (num * 1024 * 1024)
else:
s = ' ' * (num * 1024 * 1024 * 1024)
time.sleep(24 * 3600)
else:
print("bad args.....")
print_help()
# cpu usage
def deadloop():
while True:
pass
# Specify how many cores to occupy according to the parameters
def cpu():
arg = sys.argv[2] if len(sys.argv) == 3 else sys.argv[3]
cpu_num = cpu_count()
cores = int(arg)
if not isinstance(cores, int):
print("bad args not int")
return
if cores > cpu_num:
print("Invalid CPU Num(cpu_count="+str(cpu_num)+")")
return
if cores is None or cores < 1:
cores = 1
for i in range(cores):
Process(target=deadloop).start()
def mem_cpu():
Process(target=mem).start()
Process(target=cpu).start()
if __name__ == "__main__":
if len(sys.argv) >= 3:
switcher = {
'm': mem,
'c': cpu,
'mc': mem_cpu
}
switcher.get(sys.argv[1], mem)()
else:
print_help()