-
-
Save rickythefox/809f32cc07d81607e10181ad0f83b507 to your computer and use it in GitHub Desktop.
A variant of time(1) able to show real time in milliseconds and max RSS in MB.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/time.h> | |
#include <sys/types.h> | |
#include <sys/resource.h> | |
#include <sys/wait.h> | |
#include <spawn.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <unistd.h> | |
#define CHECK(cmd) if (cmd) { perror(#cmd); return 1; } | |
extern char **environ; | |
struct stats { | |
long average; | |
long min; | |
long max; | |
}; | |
struct stats stats(long values[], int n) { | |
long min = values[0]; | |
long max = values[0]; | |
long sum = 0L; | |
for (int i = 0; i < n; i++) { | |
long value = values[i]; | |
if (value < min) | |
min = value; | |
if (value > max) | |
max = value; | |
sum += value; | |
} | |
struct stats s = {sum/n, min, max}; | |
return s; | |
} | |
int main(int argc, char *const argv[]) { | |
argc--; | |
argv++; | |
int n = 1; | |
if (argv[0][0] >= '1' && argv[0][0] <= '9') { | |
n = atoi(argv[0]); | |
argc--; | |
argv++; | |
} | |
struct rusage usage; | |
struct timespec before, after; | |
long realtime[n]; | |
long memory[n]; | |
pid_t pid; | |
int status; | |
for (int i = 0; i < n; i++) { | |
CHECK(clock_gettime(CLOCK_MONOTONIC, &before)); | |
CHECK(posix_spawn(&pid, argv[0], NULL, NULL, argv, environ)); | |
CHECK(waitpid(pid, &status, 0) == -1); | |
CHECK(clock_gettime(CLOCK_MONOTONIC, &after)); | |
CHECK(getrusage(RUSAGE_CHILDREN, &usage)); | |
realtime[i] = (after.tv_sec-before.tv_sec) * 1000000000L + | |
(long) (after.tv_nsec-before.tv_nsec); | |
printf("%10ld ms\n", (realtime[i]/1000000L)); | |
memory[i] = usage.ru_maxrss; | |
printf("%10ld MB\n", memory[i]/1024L); | |
} | |
struct stats ts = stats(realtime, n); | |
struct stats ms = stats(memory, n); | |
printf("%ld [%ld-%ld] ms\n", (ts.average/1000000L), (ts.min/1000000L), (ts.max/1000000L)); | |
printf("%ld [%ld-%ld] MB\n", (ms.average/1024L), (ms.min/1024L), (ms.max/1024L)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment