0

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.

Temp4890
  • 123
  • 7
  • IF you assume the *purpose* of profiling is to find reasons for slowness, or equivalently, ways to get more speed, then this kind of timing is not a good way to do it. Rather, [*sampling the state*](http://stackoverflow.com/a/378024/23771) works better. Anything that appears on fraction X of samples, no matter how you describe it, is responsible for about that fraction of time. If you can avoid doing that, you save a corresponding fraction. The problem with timing is it is much more indirect about telling you what could be avoided. – Mike Dunlavey Mar 20 '17 at 13:28
  • It's useful because if I can know for a fact that a frame stall isn't caused by my code. Saves time on my looking for problems in my code when there isn't one. And I want per frame data and be able to isolate that specific instance, something I find sampling isn't that great at. – Temp4890 Mar 21 '17 at 15:33

1 Answers1

2

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.

Zan Lynx
  • 53,022
  • 10
  • 79
  • 131