Skip to content
Advertisement

Linux get context switch timing

I’m implementing some form of internal profiler. Is there a way to know when and for how long a thread is context switched out? I know windows has it w the event tracing api and I know perf logs how many context switches happens. Is there a way to do it on linux? Needing root privileges is not an issue since it will be an internal tool.

Advertisement

Answer

Sort of.

See http://man7.org/linux/man-pages/man2/getrusage.2.html about the getrusage() function.

Notice that the structure it returns has voluntary and involuntary context switch numbers. Also, you have user and system time. Other APIs return wall-clock time.

Any wall-clock time greater than your user and system time is time you weren’t running.

Other than that, you could probably use the kernel ftrace ability. See https://www.kernel.org/doc/Documentation/trace/ftrace.txt

Read http://www.brendangregg.com/blog/2015-07-08/choosing-a-linux-tracer.html for even more options.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement