diff --git a/sched_yield.c b/sched_yield.c new file mode 100644 index 0000000..f0d10b2 --- /dev/null +++ b/sched_yield.c @@ -0,0 +1,36 @@ +#include +#include +#include + +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; +}