Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Portable way to get system/process information #16

Closed
lh3 opened this issue Sep 24, 2018 · 2 comments
Closed

Portable way to get system/process information #16

lh3 opened this issue Sep 24, 2018 · 2 comments

Comments

@lh3
Copy link
Collaborator

lh3 commented Sep 24, 2018

The wtdbg2 algorithm is largely OS-independent. However, to collect system and process information, it assumes the OS is Linux. It would be good remove this dependency. Here are some portable ways to get the real time, CPU time and peak RAM of the current process, and the number of CPUs and total RAM of the system. These work for Mac and Linux.

#include <sys/resource.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

double cputime(void) // return in CPU seconds, including both user and system CPU time
{
	struct rusage r;
	getrusage(RUSAGE_SELF, &r);
	return r.ru_utime.tv_sec + r.ru_stime.tv_sec + 1e-6 * (r.ru_utime.tv_usec + r.ru_stime.tv_usec);
}

double realtime(void) // return in seconds
{
	struct timeval tp;
	struct timezone tzp;
	gettimeofday(&tp, &tzp);
	return tp.tv_sec + tp.tv_usec * 1e-6;
}

long peakrss(void) // return in bytes
{
	struct rusage r;
	getrusage(RUSAGE_SELF, &r);
#ifdef __linux__
	return r.ru_maxrss * 1024;
#else
	return r.ru_maxrss;
#endif
}

int ncpucore(void)
{
	return sysconf(_SC_NPROCESSORS_ONLN);
}

long totalmem(void) // return in bytes
{
	long pages = sysconf(_SC_PHYS_PAGES);
	long page_size = sysconf(_SC_PAGE_SIZE);
	return pages * page_size;
}

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
	int i, n = 1<<20, *p;
	p = (int*)calloc(n, sizeof(int));
	for (i = 0; i < n; ++i) p[i] = i;
	fprintf(stderr, "ncpu: %d\n", ncpucore());
	fprintf(stderr, "peakrss: %ld\n", peakrss());
	fprintf(stderr, "totalmem: %ld\n", totalmem());
	return 0;
}
@lh3
Copy link
Collaborator Author

lh3 commented Sep 24, 2018

PS: it is not necessary to make changes now. These functions are just something that might be useful in future.

@ruanjue
Copy link
Owner

ruanjue commented Sep 24, 2018

Thanks, Heng.

mem_share.h is a patchwork, will be split into multiple header files according function.

@ruanjue ruanjue closed this as completed Sep 24, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants