41.5. 显示进程的时间片

SCHED_RR (round-robin)策略与 SCHED_FIFO (first-in、first-in、first-out)策略稍有不同。SCHED_RR 分配以轮循轮转相同的优先级的并发进程。这样,每个进程都会分配一个时间片。sched_rr_get_interval() 函数报告分配给每个进程的时间片。

注意

虽然 POSIX 要求此功能 必须 仅处理配置为使用 SCHED_RR 调度程序策略运行的进程,sched_rr_get_interval() 函数可检索 Linux 上任何进程的时间片长度。

timeslice 信息返回为 timespec。这是自 1970 年 1 月 1 日 00:00:00 GMT 的基础时间起的秒数和纳秒:

struct timespec {
  time_t tv_sec;  /* seconds / long tv_nsec; / nanoseconds */
}

流程

显示进程的时间片:

  1. 使用以下代码创建一个测试脚本:

    #include <stdio.h>
    #include <sched.h>
    
    main()
    {
       struct timespec ts;
       int ret;
    
       /* real apps must check return values */
       ret = sched_rr_get_interval(0, &ts);
    
       printf("Timeslice: %lu.%lu\n", ts.tv_sec, ts.tv_nsec);
    }
  2. 在这些示例中,使用 sched_03 运行程序,具有不同的策略和优先级。

    $ chrt -o 0 ./sched_03
    Timeslice: 0.38994072
    $ chrt -r 10 ./sched_03
    Timeslice: 0.99984800
    $ chrt -f 10 ./sched_03
    Timeslice: 0.0

其他资源

  • nice(2) man page
  • getpriority(2) man page
  • setpriority(2) man page