Skip to content

Commit

Permalink
Add malloc-memusage sample
Browse files Browse the repository at this point in the history
  • Loading branch information
eliben committed Aug 21, 2018
1 parent 3ce93c3 commit 5555780
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 1 deletion.
4 changes: 4 additions & 0 deletions 2018/threadoverhead/Makefile
Expand Up @@ -13,6 +13,7 @@ LDFLAGS = -lpthread

EXECUTABLES = \
threadspammer \
malloc-memusage \
thread-pipe-msgpersec \
thread-switch-condvar \
thread-switch-pipe
Expand All @@ -22,6 +23,9 @@ all: $(EXECUTABLES)
threadspammer: threadspammer.c
$(CC) $(CCFLAGS) $^ -o $@ $(LDFLAGS)

malloc-memusage: malloc-memusage.c
$(CC) $(CCFLAGS) $^ -o $@ $(LDFLAGS)

thread-switch-condvar: thread-switch-condvar.c
$(CC) $(CCFLAGS) $^ -o $@ $(LDFLAGS)

Expand Down
59 changes: 59 additions & 0 deletions 2018/threadoverhead/malloc-memusage.c
@@ -0,0 +1,59 @@
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <unistd.h>

// TODO: parse and report vsz here too

void report_memory(const char* prefix) {
struct rusage ru;
if (getrusage(RUSAGE_SELF, &ru)) {
perror("getrusage");
exit(1);
}

char statusfilename[256];
snprintf(statusfilename, 256, "/proc/%d/status", getpid());

FILE* f = fopen(statusfilename, "r");
if (!f) {
perror("fopen");
exit(1);
}

char vmsizebuf[256];
char buf[256];
while (fgets(buf, 256, f)) {
if (strstr(buf, "VmSize") == buf) {
strncpy(vmsizebuf, buf + 7, 255);
char* pos = strchr(vmsizebuf, '\n');
if (pos) {
*pos = '\0';
}
break;
}
}

printf("%s: max RSS = %ld; vm size = %s\n", prefix, ru.ru_maxrss, vmsizebuf);
}


int main(int argc, char** argv) {
printf("PID = %d\n", getpid());
report_memory("started");

int N = 100 * 1024 * 1024;
char* m = malloc(N);
report_memory("after malloc");

/*for (int i = 0; i < N; ++i) {*/
/*m[i] = i;*/
/*}*/
/*report_memory("after touch");*/

printf("press ENTER\n");
(void)fgetc(stdin);
return (int)m;
}
1 change: 0 additions & 1 deletion 2018/threadoverhead/threadspammer.c
Expand Up @@ -23,7 +23,6 @@

void* threadfunc(void* p) {
// Sleep for 10 seconds total.
(void)malloc(50000);
for (int i = 0; i < 10 * 20; ++i) {
usleep(50 * 1000);
}
Expand Down

0 comments on commit 5555780

Please sign in to comment.