22import matplotlib .dates as mdates
33import datetime
44import os
5- from collections import defaultdict
65
76
87def graph_cpu_load (db_report ):
9- raw_time = []
10- raw_load = []
8+ now = datetime . datetime . now ()
9+ window_start = now - datetime . timedelta ( hours = 24 )
1110
12- for db_data in db_report :
13- raw_time .append (datetime .datetime .fromtimestamp (db_data ['timestamp' ]))
14- raw_load .append (db_data ['cpu_prcnt' ])
11+ times = []
12+ loads = []
1513
16- interval_hours = 2
17- interval_seconds = interval_hours * 3600
18- buckets = defaultdict (list )
14+ for entry in db_report :
15+ t = datetime .datetime .fromtimestamp (entry ['timestamp' ])
16+ if t >= window_start :
17+ times .append (t )
18+ loads .append (entry ['cpu_prcnt' ])
1919
20- for time_point , load_point in zip (raw_time , raw_load ):
21- timestamp = time_point .timestamp ()
22- bucket_key = int (timestamp // interval_seconds ) * interval_seconds
23- buckets [bucket_key ].append (load_point )
20+ if not times :
21+ times = [window_start , now ]
22+ loads = [0 , 0 ]
2423
25- averaged_time = []
26- averaged_load = []
24+ times , loads = zip (* sorted (zip (times , loads )))
2725
28- for bucket_timestamp in sorted (buckets .keys ()):
29- averaged_time .append (datetime .datetime .fromtimestamp (bucket_timestamp ))
30- averaged_load .append (sum (buckets [bucket_timestamp ]) / len (buckets [bucket_timestamp ]))
26+ plt .figure (figsize = (14 , 6 ))
27+ plt .title ("CPU Usage - Last 24 Hours" , fontsize = 14 , fontweight = 'bold' )
28+ plt .xlabel ("Time" , fontsize = 12 )
29+ plt .ylabel ("CPU Load (%)" , fontsize = 12 )
3130
32- plt .figure (figsize = (12 , 6 ))
33- plt .title ("CPU Usage" )
34- plt .xlabel ("Time" )
35- plt .ylabel ("Load" )
36- plt .plot (averaged_time , averaged_load , linewidth = 2 , marker = 'o' , markersize = 4 )
31+ plt .plot (times , loads , linewidth = 1.5 )
3732
38- now = datetime .datetime .now ()
39- now_rounded = now .replace (minute = 0 , second = 0 , microsecond = 0 ) + datetime .timedelta (hours = 1 )
40- twenty_four_hours_ago = (now - datetime .timedelta (hours = 24 )).replace (minute = 0 , second = 0 , microsecond = 0 )
33+ plt .grid (True , alpha = 0.5 , color = 'gray' )
34+ plt .ylim (0 , 100 )
4135
42- plt .xlim (twenty_four_hours_ago , now_rounded )
36+ ax = plt .gca ()
37+ ax .set_xlim (window_start , now )
4338
44- plt . gca () .xaxis .set_major_locator (mdates .HourLocator (interval = 2 ))
45- plt . gca () .xaxis .set_major_formatter (mdates .DateFormatter ('%H:%M' ))
39+ ax .xaxis .set_major_locator (mdates .HourLocator (interval = 2 ))
40+ ax .xaxis .set_major_formatter (mdates .DateFormatter ('%H:%M' ))
4641
4742 plt .gcf ().autofmt_xdate ()
48- plt .grid (True , alpha = 0.3 )
4943 plt .tight_layout ()
5044
51- current_dir = os .path .dirname (os .path .abspath (__file__ ))
52- graph_dir = current_dir
53- os .makedirs (graph_dir , exist_ok = True )
45+ script_dir = os .path .dirname (os .path .abspath (__file__ ))
46+ save_path = os .path .join (script_dir , 'cpu_load.png' )
5447
55- save_path = os .path .join (graph_dir , 'cpu_load.png' )
5648 print (f"Saving graph to: { save_path } " )
57-
58- plt .savefig (save_path , dpi = 150 )
59- plt .close ()
49+ plt .savefig (save_path , dpi = 150 , bbox_inches = 'tight' )
50+ plt .close ()
0 commit comments