come on Getrusage!

It contains some examples of uses of getrusage and also recollect some comments of forums

*************************************************1***********************************************

#include <sys/types.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void fibonacci()
{
FILE *f;
int nAnte,nAct,i,ii;
int c;
nAnte = 0;
nAct = 1;

/*  f= tmpfile(); */
f=fopen(“getrusage.txt”,”w+”);
fprintf(f,”Almacenará fibonacci\n”);
for(i=0;i<600;i++) {
nAnte = 0;
nAct = 1;
fprintf(f,”0″);
for(ii=i;ii>0;ii–){
c=nAnte+nAct;
nAnte=nAct;
nAct=c;
fprintf(f,” %d,”,c);
};
fprintf(f,”\n”);
if(ferror(f))    {
fprintf(stderr,”Error writing to temporary file\n”);
exit(1);
}
}

fprintf(f,”\n Fibonacci finalizado\n”);

}

int main()
{
struct rusage r_usage;
struct rlimit r_limit;
int priority;

fibonacci();

getrusage(RUSAGE_SELF,&r_usage);

printf(“CPU usage: User = %ld.%06ld,System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);

priority = getpriority(PRIO_PROCESS, getpid());
printf(“Current priority = %d\n”,priority);

getrlimit(RLIMIT_FSIZE, &r_limit);
printf(“Current FSIZE limit: soft = %ld, hard = %ld\n”,
r_limit.rlim_cur, r_limit.rlim_max);

r_limit.rlim_cur = 2048;
r_limit.rlim_max = 4096;
printf(“Setting a 2K file size limit \n”);
setrlimit(RLIMIT_FSIZE, &r_limit);

fibonacci();

exit(0);
}

*************************************************2***********************************************

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

void fibonacci()
{
int f;
int nAnte,nAct,i,ii;
int c;
nAnte = 0;
nAct = 1;
char buffer[4096];
/*  f= tmpfile(); */
f=open(“getrusage.txt”,O_RDWR |O_CREAT);
sprintf(buffer,”Almacenará fibonacci\n”);
write(f,buffer,strlen(buffer));
for(i=0;i<600;i++) {
nAnte = 0;
nAct = 1;
sprintf(buffer,”0″);
write(f,buffer,strlen(buffer));
for(ii=i;ii>0;ii–){
c=nAnte+nAct;
nAnte=nAct;
nAct=c;
sprintf(buffer,” %d,”,c);
write(f,buffer,strlen(buffer));

};
sprintf(buffer,”\n”);
write(f,buffer,strlen(buffer));

/*      if(error(f))    {
printf(stderr,”Error writing to temporary file\n”);
exit(1);
}
*/
}

sprintf(buffer,”\n Fibonacci finalizado\n”);
write(f,buffer,strlen(buffer));

}

int main()
{
struct rusage r_usage;
struct rlimit r_limit;
int priority;

fibonacci();

getrusage(RUSAGE_SELF,&r_usage);

printf(“CPU usage: User = %ld.%06ld,System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);

priority = getpriority(PRIO_PROCESS, getpid());
printf(“Current priority = %d\n”,priority);

getrlimit(RLIMIT_FSIZE, &r_limit);
printf(“Current FSIZE limit: soft = %ld, hard = %ld\n”,
r_limit.rlim_cur, r_limit.rlim_max);

r_limit.rlim_cur = 2048;
r_limit.rlim_max = 4096;
printf(“Setting a 2K file size limit \n”);
setrlimit(RLIMIT_FSIZE, &r_limit);

fibonacci();

exit(0);
}

*************************************************3***********************************************

#include <sys/types.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void fibonacci()
{
FILE *f;
int nAnte,nAct,i,ii;
int c;
nAnte = 0;
nAct = 1;

/*  f= tmpfile(); */
f=fopen(“getrusage.txt”,”w+”);
fprintf(f,”Almacenará fibonacci\n”);
for(i=0;i<600;i++) {
nAnte = 0;
nAct = 1;
fprintf(f,”0″);
for(ii=i;ii>0;ii–){
c=nAnte+nAct;
nAnte=nAct;
nAct=c;
fprintf(f,” %d,”,c);
};
fprintf(f,”\n”);
if(ferror(f))    {
fprintf(stderr,”Error writing to temporary file\n”);
exit(1);
}
}

fprintf(f,”\n Fibonacci finalizado\n”);
fclose(f);
}

int main()
{
struct rusage r_usage;
struct rlimit r_limit;
int priority;

if(fork()==0) { fibonacci(); exit(0); }

getrusage(RUSAGE_SELF,&r_usage);

printf(“CPU usage: User = %ld.%06ld,System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);

priority = getpriority(PRIO_PROCESS, getpid());
printf(“Current priority = %d\n”,priority);

getrlimit(RLIMIT_FSIZE, &r_limit);
printf(“Current FSIZE limit: soft = %ld, hard = %ld\n”,
r_limit.rlim_cur, r_limit.rlim_max);

r_limit.rlim_cur = 16384;
r_limit.rlim_max = 32767;
printf(“Setting a 32K file size limit \n”);
setrlimit(RLIMIT_FSIZE, &r_limit);

if(fork()==0) { fibonacci(); exit(0); }
wait((int*) 0);

getrusage(RUSAGE_CHILDREN,&r_usage);

printf(“Children CPU usage: User = %ld.%06ld,System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);

exit(0);
}

*************************************************4***********************************************

#include <sys/types.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void fibonacci()
{
FILE *f;
int nAnte,nAct,i,ii;
int c;
nAnte = 0;
nAct = 1;

/*  f= tmpfile(); */
f=fopen(“getrusage.txt”,”w+”);
fprintf(f,”Almacenará fibonacci\n”);
for(i=0;i<600;i++) {
nAnte = 0;
nAct = 1;
fprintf(f,”0″);
for(ii=i;ii>0;ii–){
c=nAnte+nAct;
nAnte=nAct;
nAct=c;
fprintf(f,” %d,”,c);
};
fprintf(f,”\n”);
if(ferror(f))    {
fprintf(stderr,”Error writing to temporary file\n”);
exit(1);
}
}

fprintf(f,”\n Fibonacci finalizado\n”);

}

int main()
{
struct rusage r_usage;
struct rlimit r_limit;
int priority;

fibonacci();

getrusage(RUSAGE_SELF,&r_usage);

printf(“CPU usage: User = %ld.%06ld,System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);

printf(“Memory usage = %ld\n”,r_usage.ru_maxrss);
printf(“Integral Shared Memory usage = %ld\n”,r_usage.ru_ixrss);
printf(“Integral Unshared Memory usage = %ld\n”,r_usage.ru_idrss);
printf(“Integral Unshared Stack Memory usage = %ld\n”,r_usage.ru_isrss);

priority = getpriority(PRIO_PROCESS, getpid());
printf(“Current priority = %d\n”,priority);

getrlimit(RLIMIT_FSIZE, &r_limit);
printf(“Current FSIZE limit: soft = %ld, hard = %ld\n”,
r_limit.rlim_cur, r_limit.rlim_max);

r_limit.rlim_cur = 2048;
r_limit.rlim_max = 4096;
printf(“Setting a 2K file size limit \n”);
setrlimit(RLIMIT_FSIZE, &r_limit);

fibonacci();

exit(0);
}

*************************************************5***********************************************

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

void fibonacci()
{
int f;
int nAnte,nAct,i,ii;
int c;
nAnte = 0;
nAct = 1;
char buffer[4096];
/*  f= tmpfile(); */
f=open(“getrusage.txt”,O_RDWR |O_CREAT);
sprintf(buffer,”Almacenará fibonacci\n”);
write(f,buffer,strlen(buffer));
for(i=0;i<600;i++) {
nAnte = 0;
nAct = 1;
sprintf(buffer,”0″);
write(f,buffer,strlen(buffer));
for(ii=i;ii>0;ii–){
c=nAnte+nAct;
nAnte=nAct;
nAct=c;
sprintf(buffer,” %d,”,c);
write(f,buffer,strlen(buffer));

};
sprintf(buffer,”\n”);
write(f,buffer,strlen(buffer));

/*      if(error(f))    {
printf(stderr,”Error writing to temporary file\n”);
exit(1);
}
*/
}

sprintf(buffer,”\n Fibonacci finalizado\n”);
write(f,buffer,strlen(buffer));

}

int main()
{
struct rusage r_usage;
struct rlimit r_limit;
struct timeval tinicio,tfinal;
int priority;

gettimeofday(&tinicio,NULL);
fibonacci();
getrusage(RUSAGE_SELF,&r_usage);

printf(“CPU usage: User = %ld.%06ld,System = %ld.%06ld\n”,
r_usage.ru_utime.tv_sec, r_usage.ru_utime.tv_usec,
r_usage.ru_stime.tv_sec, r_usage.ru_stime.tv_usec);

priority = getpriority(PRIO_PROCESS, getpid());
printf(“Current priority = %d\n”,priority);

getrlimit(RLIMIT_FSIZE, &r_limit);
printf(“Current FSIZE limit: soft = %ld, hard = %ld\n”,
r_limit.rlim_cur, r_limit.rlim_max);

r_limit.rlim_cur = 122048;
r_limit.rlim_max = 142096;
printf(“Setting a 2K file size limit \n”);
//    setrlimit(RLIMIT_FSIZE, &r_limit);

fibonacci();
gettimeofday(&tfinal,NULL);

printf(“tiempo con gettimeofday %f\n”,(tfinal.tv_sec+((double)tfinal.tv_usec/1000000))-(tinicio.tv_sec+((double)tinicio.tv_usec/1000000)));
//    printf(“Tiempo Final %ld.%06ld,Inicio = %ld.%06ld\n”,tfinal.tv_sec,tfinal.tv_usec,tinicio.tv_sec,tinicio.tv_usec);
exit(0);
}

*************************************************’6’***********************************************

GETRUSAGE
———
http://rabbit.eng.miami.edu/info/functions/time.html

int getrusage(int target, rusage * results)

include: <sys/time.h>
include: <sys/resource.h>
Not avalibale under DOS or Windows.

Returns 0 for success, and negative for failure; there are no reasonable
reasons for failure to occur.
The target parameter must be one of the two pre-defined values
RUSAGE_SELF or RUSAGE_CHILDREN. RUSAGE_SELF measures only the current
process, RUSAGE_CHILDREN measures only subprocesses that have already
terminated. Unix provides no useful way to obtain information for
still-running subprocesses.

The results parameter is a pointer to a struct that the calling
program must create, and which will be filled in with statistics on
resource information. The fields of this struct are as follows:
(the first two fields are structs of type timeval, see below)
ru_utime       time spent executing user code
ru_stime       time spent executing system functions
(the remaining fields are ints)
ru_maxrss      max resident set size (physical memory allocated)
ru_ixrss       memory size for code
ru_idrss       memory size for statics, globals, and new/malloc
ru_isrss       stack size (memory used by local variables)
ru_minflt      minor page faults: “page reclaims”
ru_majflt      major page faults: swaps in
ru_nswap       page swaps
ru_inblock     block input operations, disc etc
ru_oublock     block output operations, disc, etc
ru_msgsnd      messages sent
ru_msgrcv      messages received
ru_nsignals    signals received
ru_nvcsw       voluntary context switches (process loses CPU)
ru_nivcsw      involuntary context switches (process loses CPU)

The timeval struct used to measure time has only two fields, and
both are unsigned ints. They are named tv_sec and tv_usec, and
jointly represent one single value. tv_sec*1000000+tv_usec gives the
number of microseconds.

Example:
double getcputime(void)
{ struct timeval tim;
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
tim=ru.ru_utime;
double t=(double)tim.tv_sec + (double)tim.tv_usec / 1000000.0;
tim=ru.ru_stime;
t+=(double)tim.tv_sec + (double)tim.tv_usec / 1000000.0;
return t; }

This example function returns the total CPU time consumed by the current
process, measured in seconds, as a double precision floating point number.
It adds together the user time and the system time.
Note: Although the format used is capable of measuring time to an accuracy
of a microsecond, do not expect that much precision from any real system.

***************************************************************************

http://es.efreedom.com/Question/1-669438/Como-obtener-el-uso-de-memoria-en-tiempo-de-ejecucion-de-c

¿Cómo obtener el uso de memoria en tiempo de ejecución de c ++?

Hola,

necesito para obtener el uso de mem VIRT y RES en tiempo de mi programa de ejecución y mostrarlos.

Lo que he probado hasta ahora:

getrusage (http://linux.die.net/man/2/getrusage)

int who = RUSAGE_SELF;
struct rusage usage;
int ret;

ret=getrusage(who,&usage);

cout<<usage.ru_maxrss;

pero siempre recibo 0.

———-

En Linux, nunca he encontrado una solución ioctl(). Para nuestras aplicaciones, hemos codificado una rutina de utilidad general basada en la lectura de archivos en /proc/pid. Hay un número de estos archivos que dan resultados diferentes. Aquí es el que se asentaron en (la cuestión fue etiquetado de C++ y manejamos I/O mediante construcciones de C++, pero debe ser fácilmente adaptable a rutinas de e/s C si es necesario):

#include <unistd.h>
#include <ios>
#include <iostream>
#include <fstream>
#include <string>

//////////////////////////////////////////////////////////////////////////////
//
// process_mem_usage(double &, double &) – takes two doubles by reference,
// attempts to read the system-dependent data for a process’ virtual memory
// size and resident set size, and return the results in KB.
//
// On failure, returns 0.0, 0.0

void process_mem_usage(double& vm_usage, double& resident_set)
{
using std::ios_base;
using std::ifstream;
using std::string;

vm_usage     = 0.0;
resident_set = 0.0;

// ‘file’ stat seems to give the most reliable results
//
ifstream stat_stream(“/proc/self/stat”,ios_base::in);

// dummy vars for leading entries in stat that we don’t care about
//
string pid, comm, state, ppid, pgrp, session, tty_nr;
string tpgid, flags, minflt, cminflt, majflt, cmajflt;
string utime, stime, cutime, cstime, priority, nice;
string O, itrealvalue, starttime;

// the two fields we want
//
unsigned long vsize;
long rss;

stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
>> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
>> utime >> stime >> cutime >> cstime >> priority >> nice
>> O >> itrealvalue >> starttime >> vsize >> rss; // don’t care about the rest

long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
vm_usage     = vsize / 1024.0;
resident_set = rss * page_size_kb;
}

int main()
{
using std::cout;
using std::endl;

double vm, rss;
process_mem_usage(vm, rss);
cout << “VM: ” << vm << “; RSS: ” << rss << endl;
}

***************************************************************************
hello,
I’m using getrusage to tell me how much stack space I’m using as I go through a series of recursive calls. Heres the code :

struct rusage usage ;
if(getrusage(RUSAGE_CHILDREN, &usage) != 0)
{
cout<<“getrusage failed”<<endl ;
exit(0);
}

cout<<“Shared Memory = “<<usage.ru_ixrss<<endl ;
cout<<“Unshared Data Size = “<<usage.ru_idrss<<endl ;
cout<<“Unshared Stack Size = “<<usage.ru_isrss<<endl ;

However each of the outputs only produces a zero. The program I’m running will use well over 2 gigs of ram (sometimes more…argh!). I’m trying to eliminate superfluous variables by this kind if analysis.

Can anyone tell me why getrusage isn’t detecting the stack space I’m using and / or alternative methods of extracting the info I’m looking for.

Cheers,
Gearoid

http://www.linuxquestions.org/questions/programming-9/getrusage-and-process-memory-usage-499775/

*****************************************************************************

About Julita Inca

Ingeniero de Sistemas UNAC, Magíster en Ciencias de la Computación PUCP, OPW GNOME 2011, Miembro de la GNOME Foundation desde el 2012, Embajadora Fedora Perú desde el 2012, ganadora del scholarship of the Linux Foundation 2012, experiencia como Admin Linux en GMD y Especialista IT en IBM, con certificaciones RHCE, RHCSA, AIX 6.1, AIX 7 Administrator e ITILv3. Experiencia académica en universidades como PUCP, USIL y UNI. HPC researcher, a simple mortal, like you!
This entry was posted in GNU/Linux/Open Source, τεχνολογια :: Technology and tagged , , , , , . Bookmark the permalink.

One Response to come on Getrusage!

  1. Sprint family locator says:

    { Nice job, really good post mate | I will definitely recommend this to my friends | keep it up! Thanks | This is really amazing post, i think i will come back often for read some news| The post is really great, i have learned lot from this post, thank’s| thank you very much for sharing | Everything is interesting | thanks good for topic | I will definitely recommend this to my friends| This was an interesting post | quite intriguing post | Thank a lot good post!}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s