结论:重量级usleep(0) > sched_yield() > cpu_relax()
1、cpu_relax()用于短时间的忙等待,比如每个用户持锁的时间很短,让出cpu的代价不如忙等待。它和死循环等待的区别是,cpu空转功耗会低。
Note that "cpu_relax" is not a "sched_yield()". You haven't gotten to the point where you want to do a system call yet, you're way before that point. It's a "CPU core yield" - "rep nop" in x86.
2、sched_yield会调用sched_yield系统调用。
所以一定会陷入内核态,触发任务切换。
3、usleep(n)会调用nanosleep系统调用
所以一定会陷入内核态,调用deactivate_task触发任务调度,然后进行任务切换。而任务调度是比较耗时的。
https://www.cnblogs.com/schips/p/11002589.html
Real World Technologies - Forums - Thread: Nuances related to Spinlock implementation and the Linux Scheduler
性能优化之sleep、sched_yield和忙等待 - 简书