11#include "analyzer.h"
22#include "cputracker.h"
33
4+
5+ unsigned long average_cpu_usage (struct proc_stat prev , struct proc_stat next ){
6+ unsigned long prev_idle = prev .idle + prev .iowait ;
7+ unsigned long idle = next .idle + next .iowait ;
8+
9+ unsigned long prev_non_idle = prev .user + prev .nice + prev .system + prev .irq + prev .softirq + prev .steal ;
10+ unsigned long non_idle = next .user + next .nice + next .system + next .irq + next .softirq + next .steal ;
11+
12+ unsigned long prev_total = prev_idle + prev_non_idle ;
13+ unsigned long total = idle + non_idle ;
14+
15+ total -= prev_total ;
16+ idle -= prev_idle ;
17+
18+ return (total - idle )* 100 /total ;
19+ }
20+
21+
422void * analyzer () {
23+ struct proc_stat * prev = malloc (g_nproc * sizeof (struct proc_stat ));
24+ struct proc_stat * stats = NULL ;
525 while (1 ) {
626 sem_wait (& g_filledSpaceSemaphore );
27+
728 pthread_mutex_lock (& g_bufferMutex );
829
9- struct proc_stat * stats = get_item ();
30+ stats = get_item_from_buffer ();
31+ for (int i = 0 ; i < g_nproc ; i ++ ){
32+ printf ("%lu " , average_cpu_usage (prev [i ], stats [i ]));
33+ prev [i ] = stats [i ];
34+ }
1035
36+ printf ("\n" );
1137 pthread_mutex_unlock (& g_bufferMutex );
12- sem_post (& g_leftSpaceSemaphore );
1338
14- for (int i = 0 ; i < g_nproc ; i ++ ) {
15- printf ("%s %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n" , stats [i ].name ,
16- stats [i ].user , stats [i ].nice , stats [i ].system , stats [i ].idle ,
17- stats [i ].iowait , stats [i ].irq , stats [i ].softirq , stats [i ].steal ,
18- stats [i ].guest , stats [i ].guest_nice );
19- }
39+ sem_post (& g_leftSpaceSemaphore );
2040 }
2141}
0 commit comments