linux下usleep函数对CPU占用率的影响
2023-11-16
文章目录
- linux下usleep函数对CPU占用率的影响
- 1. 测试代码
- 2. CPU占用率
- 不使用usleep延时
- #define SLEEP_US 1 (1微秒)
- #define SLEEP_US 10 (10微秒)
- #define SLEEP_US 100 (100微秒)
- #define SLEEP_US 1000 (1000微秒=1毫秒)
- #define SLEEP_US 10000 (10000微秒=10毫秒)
- #define SLEEP_US 100000 (100000微秒=100毫秒)
环境
系统: ubuntu 22.04
内核版本: Linux 5.15.0-58-generic
cpu: Intel(R) Xeon(R) Platinum 8269CY CPU @ 2.50GHz
cpu核数: 1
架构: x86_64
1. 测试代码
main.cpp
#include <unistd.h> // usleep#define SLEEP_US 1int main()
{while (1){usleep(SLEEP_US);}return 0;
}
$ g++ main.cpp -o main
$ ./main
$ top -p `pidof main`
2. CPU占用率
不使用usleep延时
CPU占用率:95.3%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2325638 root 20 0 2640 940 848 R 95.3 0.1 0:29.17 main
#define SLEEP_US 1 (1微秒)
CPU占用率:8.0%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2324270 root 20 0 2640 928 840 R 8.0 0.1 0:07.92 main
#define SLEEP_US 10 (10微秒)
CPU占用率:7.0%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2326872 root 20 0 2640 976 888 R 7.0 0.1 0:01.61 main
#define SLEEP_US 100 (100微秒)
CPU占用率:3.3%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2327593 root 20 0 2640 988 900 R 3.3 0.1 0:00.73 main
#define SLEEP_US 1000 (1000微秒=1毫秒)
CPU占用率:0.7%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2328327 root 20 0 2640 984 896 S 0.7 0.1 0:00.15 main
#define SLEEP_US 10000 (10000微秒=10毫秒)
CPU占用率:0.3%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2329099 root 20 0 2640 988 900 S 0.3 0.1 0:00.02 main
#define SLEEP_US 100000 (100000微秒=100毫秒)
CPU占用率:0.0%
$ top -p `pidof main`PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND
2329719 root 20 0 2640 984 896 S 0.0 0.1 0:00.00 main
License
License under CC BY-NC-ND 4.0: 署名-非商业使用-禁止演绎
Reference:
NULL