36 lines
896 B
C
36 lines
896 B
C
#include <sched.h>
|
|
#include <stdio.h>
|
|
#include <time.h>
|
|
|
|
struct timespec ts = {.tv_nsec = 30, .tv_sec = 0};
|
|
volatile int dummy = 0;
|
|
|
|
int main(int argc, char *argv[]) {
|
|
struct timespec start, end;
|
|
|
|
clock_gettime(CLOCK_MONOTONIC, &start);
|
|
|
|
for (int a = 0; a < 10000; a++) {
|
|
// Keep in mind that yield is a syscall, it does not sleep, but places
|
|
// the process at the end of the run queue and gives other threads a
|
|
// chance to run.
|
|
sched_yield();
|
|
dummy++; // Do some stuff to the dummy to avoid optimizations
|
|
|
|
nanosleep(&ts, NULL);
|
|
|
|
printf("Iteration %d\n", a);
|
|
fflush(stdout);
|
|
}
|
|
|
|
clock_gettime(CLOCK_MONOTONIC, &end);
|
|
|
|
long sec = end.tv_sec - start.tv_sec;
|
|
long nanos = end.tv_nsec - start.tv_nsec;
|
|
|
|
double elapsed = sec + nanos * 1e-9;
|
|
|
|
printf("Elapsed time: %.2fs\n", elapsed);
|
|
|
|
return 0;
|
|
}
|