进程调度(进程优先级和nice值)

来源:互联网 发布:淘宝商家怎么进天猫 编辑:程序博客网 时间:2024/06/08 12:53

基本概念:

进程优先级是一个数值,它通过动态的优先级和静态的优先级来决定进程被CPU处理的顺序。一个拥有更高进程优先级的进程拥有更大的机率得到处理器的处理。

内核根据进程的行为和特性使用试探算法,动态地调整调高或调低动态优先级。一个用户进程可以通过使用进程的nice值间接改变静态优先级。一个拥有更高静态优先级的进程将会拥有更长的时间片(进程能在处理上运行多长时间)。


Linux支持从19(最低优先级)到-20(最高优先级)的nice值。默认值为0。


进程可以通过调整nice值选择以更低优先级运行。


    #include <sys/time.h>  

       #include <sys/resource.h>  

  

       int getpriority(int which, int who);  

       int setpriority(int which, int who, int prio);  




例子,调整nic值,比较相同的任务两个进程的耗时。gcc nice.c


#include <unistd.h>  

#include <stdio.h>  

#include <sys/time.h>  

#include <sys/resource.h>  

#include <time.h>  

  

  

int main()  

{  

    time_t t1, t2, t3;  

    time(&t1);  

  

  

    int i = 0;  

    int num = 10000;  

  

  

    pid_t pid = fork();  

  

  

    if (pid == 0) {  

        int nice = getpriority(PRIO_PROCESS, 0);  

        printf("parent nice = %d\n", nice);  

        for (i; i<num; --i)  

            ;  

        time(&t2);  

        printf("parent pay %ld sec\n", t2-t1);  

    } else if (pid > 0) {  

        setpriority(PRIO_PROCESS, 0, 19);  

        int nice = getpriority(PRIO_PROCESS, 0);  

        printf("child nice = %d\n", nice);  

        for (i; i<num; --i)  

            ;  

        time(&t3);  

        printf("child pay %ld sec\n", t3-t1);  

    } else {  

        perror("fork fail");  

        return -1;  

    }  

  

    sleep(20);  

    return 0;  

}  


在centos 7运行,有效:




在unubtu 14运行,有效:



通过top命令可以看到当前进程的nice值:



阅读全文
0 0