Skip to content

Instantly share code, notes, and snippets.

@makotoshimazu
Last active April 5, 2018 07:46
Show Gist options
  • Save makotoshimazu/55f69ffcbec0b31dd25f8936e4a764c6 to your computer and use it in GitHub Desktop.
Save makotoshimazu/55f69ffcbec0b31dd25f8936e4a764c6 to your computer and use it in GitHub Desktop.
namespace {
extern "C" {
#include <linux/sched.h>
#include <linux/kernel.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/types.h>
#include <sched.h>
#include <linux/sched.h>
#include <sys/types.h>
struct sched_attr {
__u32 size;
__u32 sched_policy;
__u64 sched_flags;
/* SCHED_NORMAL, SCHED_BATCH */
__s32 sched_nice;
/* SCHED_FIFO, SCHED_RR */
__u32 sched_priority;
/* SCHED_DEADLINE */
__u64 sched_runtime;
__u64 sched_deadline;
__u64 sched_period;
};
int sched_setattr(
pid_t pid, const struct sched_attr *attr, unsigned int flags) {
return syscall(__NR_sched_setattr, pid, attr, flags);
}
int sched_getattr(
pid_t pid, struct sched_attr *attr, unsigned int size, unsigned int flags) {
return syscall(__NR_sched_getattr, pid, attr, size, flags);
}
} // extern "C"
} // namespace
#include <sys/time.h>
#include <iostream>
#include <cstring>
void loop() {
static uint64_t s_prev_us = 0;
struct timeval tv;
gettimeofday(&tv, nullptr);
uint64_t us = tv.tv_sec * 1E6 + tv.tv_usec;
std::cout << "Now: " << us / 1000 << " diff (us): " << us - s_prev_us << std::endl;
s_prev_us = us;
return;
}
int set_scheduler_to_deadline() {
const uint64_t ms_in_ns = 1000000;
sched_attr attr {
.size = sizeof(sched_attr),
.sched_policy = SCHED_DEADLINE,
.sched_flags = SCHED_FLAG_RESET_ON_FORK,
.sched_nice = 0 /* Not used for DEADLINE. */,
.sched_priority = 0 /* Not used for DEADLINE. */,
.sched_runtime = 1 * ms_in_ns /* 1 ms */,
.sched_deadline = 2 * ms_in_ns /* 2 ms */,
.sched_period = 10 * ms_in_ns /* 10 ms */
};
return sched_setattr(0 /* pid */, &attr, 0 /* flags */);
}
int main() {
int rc = set_scheduler_to_deadline();
if (rc != 0) {
std::cerr << "Failed to set schedular params: "
<< strerror(errno) << std::endl;
return 1;
}
std::cout << "Set the schedular to DEADLINE." << std::endl;
while (true) {
loop();
sched_yield();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment