Skip to content

Commit c7bd47c

Browse files
author
yuxuemin
committed
simulate memory cpu use
1 parent ef1fecc commit c7bd47c

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

simulate_memory_cpu.py

+81
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#! /user/bin/env python
2+
# -*- encoding: utf-8 -*-
3+
"""
4+
Simulate cpu、 memory usage
5+
"""
6+
7+
import sys
8+
import re
9+
import time
10+
from multiprocessing import Process, cpu_count
11+
12+
13+
def print_help():
14+
print('Usage: ')
15+
print(' python cpu_memory_simulator.py m 1GB')
16+
print(' python cpu_memory_simulator.py c 1')
17+
print(' python cpu_memory_simulator.py mc 1GB 2')
18+
19+
# memory usage
20+
21+
22+
def mem():
23+
pattern = re.compile('^(\d*)([M|G]B)$')
24+
size = sys.argv[2].upper()
25+
match = pattern.match(size)
26+
if match:
27+
num = int(match.group(1))
28+
unit = match.group(2)
29+
if unit == 'MB':
30+
s = ' ' * (num * 1024 * 1024)
31+
else:
32+
s = ' ' * (num * 1024 * 1024 * 1024)
33+
time.sleep(24 * 3600)
34+
else:
35+
print("bad args.....")
36+
print_help()
37+
38+
# cpu usage
39+
40+
41+
def deadloop():
42+
while True:
43+
pass
44+
45+
# Specify how many cores to occupy according to the parameters
46+
47+
48+
def cpu():
49+
arg = sys.argv[2] if len(sys.argv) == 3 else sys.argv[3]
50+
cpu_num = cpu_count()
51+
cores = int(arg)
52+
if not isinstance(cores, int):
53+
print("bad args not int")
54+
return
55+
56+
if cores > cpu_num:
57+
print("Invalid CPU Num(cpu_count="+str(cpu_num)+")")
58+
return
59+
60+
if cores is None or cores < 1:
61+
cores = 1
62+
63+
for i in range(cores):
64+
Process(target=deadloop).start()
65+
66+
67+
def mem_cpu():
68+
Process(target=mem).start()
69+
Process(target=cpu).start()
70+
71+
72+
if __name__ == "__main__":
73+
if len(sys.argv) >= 3:
74+
switcher = {
75+
'm': mem,
76+
'c': cpu,
77+
'mc': mem_cpu
78+
}
79+
switcher.get(sys.argv[1], mem)()
80+
else:
81+
print_help()

0 commit comments

Comments
 (0)