Nice value in linux

What does the «nice» value mean in CPU utilization statistics

I am relatively new to Linux and Ubuntu. I have attached the system monitor to the bar (the upper bar of the screen) and opened the preference to configure this gadget. On the processor tab I see that I can mark the choose 5 colors : user, system, nice, IOwait and idle. I can understand all 4 (I think. ) except for «nice». What is this «nice» ? I read this answer and I understand that the superuser can perform tasks with greater priority but , what does it mean if I see it in the system monitor without me running any new nice processes ?

This question is about the CPU’s nice value, not a particular process’ nice value. The Q&A flagged as the duplicate of this only deals with the nice value of a process not whit the nice value of the CPU utilization. Those are of course related but not the same thing. So I think this is not a duplicate of that one.

2 Answers 2

The nice value for the processor is

the time the CPU has spent running users’ processes that have been «niced».

(from man top ) A «niced» process is one with a positive nice value. So if the processor’s nice value is high, that means it is working with some low priority processes. So this indicator is useful when you see high CPU utilization and you are afraid that this high load will have bad effect on your system:

  • High CPU utilization with high nice value: Nothing to worry, not so important tasks doing their job, important processes will easily get CPU time if they need. This situation is not a real bottleneck.
  • High CPU utilization with low nice value: Something to worry because the CPU is stressed with important processes so these or new processes will have to wait. This situation is a real bottleneck.

I think this nice value is not too important for a simple user, this is more useful in a server environment.

Источник

Команда nice, или вежливые процессы

Когда на компьютере достаточно процессорного времени на исполнение всех процессов, нет необходимости в выставлении приоритетов. Но когда необходимо параллельно запустить несколько процессов, каждый из которых использует всё доступное процессорное время, может очень пригодиться утилита nice.

Команда nice запускает программу с изменённым приоритетом для планироващика задач. Слово «nice» в английском языке обозначает, в частности, «вежливый». По этимологии этой команды процесс с большим значением nice — более вежлив к другим процессам, позволяя им использовать больше процессорного времени, поскольку он сам имеет меньший приоритет (и, следовательно, большее «значение вежливости» — niceness value).

Наибольший приоритет (и наименьшее значение nice) — −20. 19, либо 20 — наименьший приоритет, но это, с другой стороны, самые вежливые процессы.

Чтобы посмотреть идентификатор и значение nice нужного процесса в системе, можно воспользоваться командой ps axl.

Пример использования команды nice — запуск ресурсоёмкой задачи в фоновом режиме, так, чтобы она выполнялась, но освобождала часть процессорного времени для других процессов, как только оно становятся им нужно. Таким образом можно, скажем, запустить кодирование OGG/MP3 с большим значением nice, чтобы оно происходило в фоновом режиме, используя не всё процессорное время, а то, что не используется другими процессами (с меньшим значением nice — то есть с большим приоритетом).

Читайте также:  Перевернуто изображение камеры linux

Чтобы запустить команду с определённым приоритетом, слева нужно добавить «nice -n значение_nice», либо «nice —adjustment значение_nice» (adjustment — настройка, регулировка).

То есть: nice -n значение_nice команда.

Если нужно изменить приоритет уже запущенного процесса, можно воспользоваться командой renice.

renice -n значение_nice id_процесса

Команда renice выводит старый и новый приоритет процесса.

Теперь, зная эти команды, можно управлять процессами так, чтобы определённые задачи выполнялись быстрее в случае, когда сразу много процессов используют всё доступное процессорное время.

Источник

Process ‘niceness’ vs. ‘priority’

There are two values that I am interested in: PR (Priority) and NI (Niceness). If I understood what I already found out correctly, both determine how much CPU time a process will get in contrast to other processes. But what is the difference between those values then? Could you also please describe how to manipulate those values of a process and under which circumstances this might be useful?

3 Answers 3

Nice value is a user-space and priority PR is the process’s actual priority that use by Linux kernel. In linux system priorities are 0 to 139 in which 0 to 99 for real time and 100 to 139 for users. nice value range is -20 to +19 where -20 is highest, 0 default and +19 is lowest. relation between nice value and priority is :

so , the value of PR = 20 + (-20 to +19) is 0 to 39 that maps 100 to 139.

PR — Priority The scheduling priority of the task. If you see ‘rt’ in this field, it means the task is running under ‘real time’ scheduling priority.

NI — Nice Value The nice value of the task. A negative nice value means higher priority, whereas a positive nice value means lower priority.Zero in this field simply means priority will not be adjusted in determining a task’s dispatch-ability

Edit: By default when a program is launched in Linux, it gets launched with the priority of ‘0’. However you can change the priority of your programs by either of the following methods.

    You can launch a program with your required priority using

nice -n nice_value program_name 
renice -n nice_value -p process_id 

Are you saying, they are almost the same thing in reverse (both represent priority) BUT niceness can be used to give a negative priority so that task with the niceness gets out of the way of high priority tasks ? (ie it is being nice and letting other access resources ? Or did this just confuse me ?

An example of what I mean, two tasks, both have pr of 20, so equal, task one has a ni of 0 and task two has an ni of 20, so, this would mean that task two would give up resources for task one because it is nicer

As i know , priority calculated as PR = 20 + NI . so task one priority = 20 +0 . maximum value of nice will +19

PR=20+NI maximum value can be 39 . actually in linux system there is 139 priority in which 0 to 99 is real time priority and for user there is 100 to 139 . so , NI value -20 to +19 maps to priority 100 to 139 . that you can adjust . but still kernel not sure if you change NI value then it will change priority , NI value is a just suggestion to kernel . kernel some time ignore it

Читайте также:  Program on windows and linux

So is PR and NI are actually equivalent, as they’ve just a different offset? Why do we have both values then? And you could add that setting niceness of a process

What is Priority and Why Should I Care?

When talking about processes priority is all about managing processor time. The Processor or CPU is like a human juggling multiple tasks at the same time. Sometimes we can have enough room to take on multiple projects. Sometimes we can only focus on one thing at a time. Other times something important pops up and we want to devote all of our energy into solving that problem while putting less important tasks on the back burner.

In Linux we can set guidelines for the CPU to follow when it is looking at all the tasks it has to do. These guidelines are called niceness or nice value. The Linux niceness scale goes from -20 to 19. The lower the number the more priority that task gets. If the niceness value is high number like 19 the task will be set to the lowest priority and the CPU will process it whenever it gets a chance. The default nice value is zero.

By using this scale we can allocate our CPU resources more appropriately. Lower priority programs that are not important can be set to a higher nice value, while high priority programs like daemons and services can be set to receive more of the CPU’s focus. You can even give a specific user a lower nice value for all of his/her processes so you can limit their ability to slow down the computer’s core services.

Set the priority for new processes with nice , eg

renice 10 -p $(pgrep firefox) 
renice -1 -p $(pgrep firefox) renice: failed to set priority for 2769 (process ID): Permission denied 
% ps -o pid,comm,pri,nice -p $(pgrep firefox) PID COMMAND PRI NI 2769 firefox 19 0 % renice 10 -p 2769 # note, we don't need sudo here 2769 (process ID) old priority 0, new priority 10 % ps -o pid,comm,pri,nice -p $(pgrep firefox) PID COMMAND PRI NI 2769 firefox 9 10 % sudo renice -19 -p 2769 2769 (process ID) old priority 10, new priority -19 % ps -o pid,comm,pri,nice -p $(pgrep firefox) PID COMMAND PRI NI 2769 firefox 38 -19 

To renice all running processes for a specific user

Источник

How to use nice Command in Linux?

Nice Command Featured Image

This article talks about the nice command in Linux. In Linux, each process has a nice value granted to it. This value influences the scheduling of processes and thereby determining the amount of CPU to spent on each one of them. “The more the nice value, the less the supposed priority”. This ultimately means that the more the process is nice, the more it allows other processes to get CPU.

The nice value ranges from -20 to 19 where -20 means a process is not nice, therefore must be given more priority, and 19 is the nicest process, therefore allows other processes to access resources before itself.

Читайте также:  Calculate linux to gentoo

There is yet another priority in play, which denotes the actual priority in the eyes of the kernel. The Nice Value is not a real-time priority value but can be considered as a hint to the kernel about what range of priority a particular process should have.

Monitoring the nice value

We can not influence the value before monitoring it. Therefore, Linux has a set of system monitoring commands like top, atop, and htop that can be used to figure out nice values for every process in the system.

Using the standard top command

top is a simple command that provides information about the utilization of the system’s resources by each process. This includes knowledge related to CPU scheduling. By typing top in the terminal we get:

Nice Command Top Output Edited

The two adjoining columns denote the priority-related values for every process. The PR column denotes the actual kernel-given priority of the process, whereas the NI column provides the Nice Value for each process. We have a complete article based on the top command if the user wants to gain further knowledge about it.

Using the htop command

htop is an interactive tool for displaying the usage of the system’s resources. It supports searching and filtering of values for the user’s convenience. We have to simply enter htop to obtain all the relevant information.

Nice Command Htop Output 1

The fourth column denotes the nice value. This utility sorts the processes on a click on a specific column name. In the above figure, all the processes are sorted in decreasing order of nice value. Curious readers can visit here for more information about htop command.

Display the current niceness

The nice command without any parameters display the nice value of the bash running on the terminal.

Nice Command Niceness

As seen in the above figure, the default value is set to 0 . This implies that any command running using this terminal will have the same nice value.

Standard usage of nice command in Linux

The nice command can be used to start a process with a nice value specified by the user. This basically alters the actual priority assigned by the kernel.

Let us run an example for efficient understanding:

Nice Command Usage

In the above snippet, we initiate the htop utility with a nice value of -10 . We can refer the result in the command’s output:

Nice Command Usage Edited 1

By default, htop runs with a nice value of 0 . It must be duly noted that to run a command with nice value less than 0, the root permissions are necessary.

Set a nice value for the bash

Instead of using nice command for every process we create, we can set a particular nice value to the current bash. It is done by:

Nice Command Set Bash

The result can be noticed using the same htop command initiated above:

Nice Command Set Htop 1

The htop command inherited the nice value of the bash which was used to run it.

Conclusion

Though the nice command has a simple usage and rather less technicality, but it stands out as a crucial command in the context of process scheduling. We have a bunch of articles on Linux commands which are worth a read. Make sure you check them out.

Источник

Оцените статью
Adblock
detector