Swapna Chalavindala
Swapna Chalavindala

Reputation: 89

Why is kernel code faster than user code?

Why can kernel code run faster than user code? I have heard that user code may be written in the C language, and also that kernel code may be written in C, such as in Windows. Then what is the reason for faster execution in kernel mode?

Upvotes: 1

Views: 3031

Answers (1)

Lithis
Lithis

Reputation: 1377

In general, code that runs in kernel space runs at the same speed as code in user space. For example, if you implemented a sin function from scratch to calculate the sine of an angle, it would run at the same speed in either case.

Where code can run faster in kernel space is when system calls are made. When user mode code calls a system function, the OS switches into supervisor mode, and this transition can be slow. Code running in kernel space is already in supervisor mode, so no mode switch is necessary. On some operating systems, making a system call from user space can also result in a slow context switch.

In the example of a sin function, if you added logging statements to the function that made a system call to write to a file, the sin function would now be faster if it was running in kernel mode.

For more information, see the following Wikipedia articles and sections:

Upvotes: 14

Related Questions