Ed eccoci arrivati alla seconda puntata di iMemory. In questo capitolo, vedremo come approfondire la nostra applicazione iMemory inserendo il calcolo della CPU (Central Processing Unit ovvero Unità centrale di elaborazione).

Per prima cosa apriamo l’applicazione iMemory e modifichiamo la window come mostrato in figura.
Schermata 08-2455805 alle 12.31.10.png

Ok. Adesso modifichiamo il file AppController.h ovvero il file di intestazione nel seguente modo:

 

 

#import <Cocoa/Cocoa.h>
#define GiB (1024*1024*1024)        // 1 Gibibyte di RAM
@interface AppController : NSObject{

//RAM//

IBOutlet NSTextField *ramInstallata; //Totale Memoria Ram Installata sul computer
IBOutlet NSTextField *ramLibera;     //Memoria ancora libera
IBOutlet NSTextField *ramWired;     //Memoria ancora wired
IBOutlet NSTextField *ramInattiva;     //Memoria ancora inattiva
IBOutlet NSTextField *ramAttiva;     //Memoria ancora Attiva
//Per il calcolo della dimensione della memoria libera, wired, inattiva e attiva
vm_statistics_data_t    vm_stat;    //Struttura contenente le informazioni relative alla situazione della memoria
vm_size_t vm_size; //Dimensione di una pagina di memoria
mach_port_t myHost; //Port per accedere alle chiamate Mach-Os  per sapere quanta Ram c’e’ installata
double nInstalledMemory; //Dimensione della memoria installata in GiB
double nFreeMemory; //Dimensione della memoria libera in MiB
double nInattivaMemory; //Dimensione della memoria inattiva in MiB
double nAttivaMemory; //Dimensione della memoria attiva in MiB
double nWiredMemory; //Dimensione della memoria wired in MiB

//CPU//
double nCpuInattiva;//percentuale della CPU inattiva
double nCpuUtente;//percentuale della CPU dell’utente
double nCpuSistema;//percentuale della CPU di sistema
IBOutlet NSTextField *cpuInattiva;
IBOutlet NSTextField *cpuUtente;
IBOutlet NSTextField *cpuSistema;

//ALTRO//
NSTimer *updateFreeMemory; //Timer per aggiornare informazioni sulle memorie e sulla CPU

}
– (void) memoryStatisticst;  //Leggo informazioni statistiche relative alla Ram e alla CPU

– (void) awakeFromNib; //Chiamata in automatico appena il file NIB viene caricato in memoria

 

– (void)timerFireMethod:(NSTimer*)theTimer; //Metodo richiamato dal timer che ho impostato allo scadere del tempo

@end
Una volta terminato di modificare il file AppController.h, colleghiamo i vari IBOutlet ai rispettivi oggetti in MainMenu.xib.
Bene. Adesso è giunta l’ora di implementare il metodo memoryStatisticst nel seguente modo:
– (void) memoryStatisticst{
//————————————————————————-
// Memoria Installata
//————————————————————————-
int error = 0 ;
uint64_t value = 0 ;
unsigned long length = sizeof(value) ;
int selection[2] = { CTL_HW, HW_MEMSIZE } ;
error = sysctl(selection, 2, &value, &length, NULL, 0) ;
if ( error == 0 ){ //Ok, ho il valore il bytes lo trasformo in GiB
nInstalledMemory=((double)value / GiB);
}else{
nInstalledMemory=0.0;
}
//————————————————————————-
//————————————————————————-
// Memoria Libera e altre
//————————————————————————-
myHost = mach_host_self();
if(host_page_size(mach_host_self(), &vm_size) != KERN_SUCCESS) {
NSLog(@”Errore durante esecuzione di host_page_size”);
vm_size = 4096; //Valore di default
}
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_stat, &count) != KERN_SUCCESS) {
NSLog(@”Errore durante esecuzione di host_statistics”);
nFreeMemory=0.0;
}else{
nFreeMemory=((double) (vm_stat.free_count) * vm_size) /(1024*1024);
nAttivaMemory=((double) (vm_stat.active_count) * vm_size) /(1024*1024);
nWiredMemory=((double) (vm_stat.wire_count) * vm_size) /(1024*1024);
nInattivaMemory=((double) (vm_stat.inactive_count) * vm_size) /(1024*1024);
}
//————————————————————————-

//Aggiorno informazioni utente
[ramInstallata setStringValue:[NSString stringWithFormat:@”%.2f GiB”,nInstalledMemory]];
[ramLibera setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nFreeMemory]];
[ramWired setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nWiredMemory]];
[ramAttiva setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nAttivaMemory]];
[ramInattiva setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nInattivaMemory]];

//CPU//

mach_port_t host_port;
host_cpu_load_info_data_t prev_cpu_load, cpu_load;
mach_msg_type_number_t countcpu = HOST_CPU_LOAD_INFO_COUNT;
natural_t user, system, idle;

host_port = mach_host_self();
host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&prev_cpu_load, &countcpu);
sleep(1);

// Acquisizione del tempo della CPU

host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&cpu_load, &countcpu);

//Calcolare la percentuale della CPU
user = cpu_load.cpu_ticks[CPU_STATE_USER] – prev_cpu_load.cpu_ticks[CPU_STATE_USER];
system = cpu_load.cpu_ticks[CPU_STATE_SYSTEM] – prev_cpu_load.cpu_ticks[CPU_STATE_SYSTEM];
idle = cpu_load.cpu_ticks[CPU_STATE_IDLE] – prev_cpu_load.cpu_ticks[CPU_STATE_IDLE];
nCpuInattiva = (double)idle/ (system + user + idle) *100.0;
nCpuSistema = (double)system / (system + user + idle)* 100.0;
nCpuUtente = (double)user / (system + user + idle)* 100.0;
[cpuSistema setStringValue:[NSString stringWithFormat:@”%.2f %%”,nCpuSistema]];
[cpuInattiva setStringValue:[NSString stringWithFormat:@”%.2f %%”,nCpuInattiva]];
[cpuUtente setStringValue:[NSString stringWithFormat:@”%.2f %%”,nCpuUtente]];
// Aggiornamento
prev_cpu_load = cpu_load;

}

 

 

Se abbiamo fatto tutto correttamente, facendo Build & Run comparirà la finestra, la quale ci indicherà lo stato attuale della memoria e della CPU.

Però un ‘altro problema c’è : la nostra applicazione iMemory va lenta.
Allora è il caso di parallelizzare i thread.
Questo accade perchè l’analisi della CPU e quindi il calcolo, richiede molto tempo per darci i risultati. Quindi la soluzione è scrivere questo nel metodo memoryStatisticst:

 

 

– (void) memoryStatisticst{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{
//————————————————————————-
// Memoria Installata
//————————————————————————-
int error = 0 ;
uint64_t value = 0 ;
unsigned long length = sizeof(value) ;
int selection[2] = { CTL_HW, HW_MEMSIZE } ;
error = sysctl(selection, 2, &value, &length, NULL, 0) ;
if ( error == 0 ){ //Ok, ho il valore il bytes lo trasformo in GiB
nInstalledMemory=((double)value / GiB);
}else{
nInstalledMemory=0.0;
}
//————————————————————————-

//————————————————————————-
// Memoria Libera e altre
//————————————————————————-
myHost = mach_host_self();
if(host_page_size(mach_host_self(), &vm_size) != KERN_SUCCESS) {
NSLog(@”Errore durante esecuzione di host_page_size”);
vm_size = 4096; //Valore di default
}
mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
if (host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vm_stat, &count) != KERN_SUCCESS) {
NSLog(@”Errore durante esecuzione di host_statistics”);
nFreeMemory=0.0;
}else{
nFreeMemory=((double) (vm_stat.free_count) * vm_size) /(1024*1024);
nAttivaMemory=((double) (vm_stat.active_count) * vm_size) /(1024*1024);
nWiredMemory=((double) (vm_stat.wire_count) * vm_size) /(1024*1024);
nInattivaMemory=((double) (vm_stat.inactive_count) * vm_size) /(1024*1024);
}
//————————————————————————-

//Aggiorno informazioni utente
[ramInstallata setStringValue:[NSString stringWithFormat:@”%.2f GiB”,nInstalledMemory]];
[ramLibera setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nFreeMemory]];
[ramWired setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nWiredMemory]];
[ramAttiva setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nAttivaMemory]];
[ramInattiva setStringValue:[NSString stringWithFormat:@”%.2f MiB”,nInattivaMemory]];

mach_port_t host_port;
host_cpu_load_info_data_t prev_cpu_load, cpu_load;
mach_msg_type_number_t countcpu = HOST_CPU_LOAD_INFO_COUNT;
natural_t user, system, idle;

host_port = mach_host_self();
host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&prev_cpu_load, &countcpu);
sleep(1);

// Acquisizione di tempo della CPU

host_statistics(host_port, HOST_CPU_LOAD_INFO, (host_info_t)&cpu_load, &countcpu);

//calcolare la percentuale della CPU
user = cpu_load.cpu_ticks[CPU_STATE_USER] – prev_cpu_load.cpu_ticks[CPU_STATE_USER];
system = cpu_load.cpu_ticks[CPU_STATE_SYSTEM] – prev_cpu_load.cpu_ticks[CPU_STATE_SYSTEM];
idle = cpu_load.cpu_ticks[CPU_STATE_IDLE] – prev_cpu_load.cpu_ticks[CPU_STATE_IDLE];
nCpuInattiva = (double)idle/ (system + user + idle) *100.0;
nCpuSistema = (double)system / (system + user + idle)* 100.0;
nCpuUtente = (double)user / (system + user + idle)* 100.0;
[cpuSistema setStringValue:[NSString stringWithFormat:@”%.2f %%”,nCpuSistema]];
[cpuInattiva setStringValue:[NSString stringWithFormat:@”%.2f %%”,nCpuInattiva]];
[cpuUtente setStringValue:[NSString stringWithFormat:@”%.2f %%”,nCpuUtente]];
// Aggiornamento
prev_cpu_load = cpu_load;
     dispatch_async(dispatch_get_main_queue(), ^{
});
});


}

Bene, abbiamo concluso la nostra applicazione.

Per chi volesse il progetto completo mi scriva nella mail: mikypio98@gmail.com