user79126
user79126

Reputation: 181

Linux/C: Check if context switch has occurred from inside thread

In a Linux/GNU/C environment, is there any visibility a running thread has into whether it has been put to sleep. For example say you have a function like

void foo() {
  startClock();
  bar();   
  endClock();
}

But you're only concerned with the running time of the code itself. I.e. you don't care about any time related to the thread being suspended during the run. Ideally you'd be able to leverage some system call or library, like countThreadSwitches(), such that:

void foo() {
  int lastCount = countThreadSwitches();
  startClock();
  bar();
  endClock();
  if (countThreadSwitches() != lastCount)
    discardClock();

}

Being able to tell whether the thread has switched in between two statements, would allow us to only measure runs unaffected by context switches.

So, is there anything like that hypothetical countThreadSwitches() call? Or is that information opaque to the thread itself?

Upvotes: 3

Views: 1955

Answers (2)

caf
caf

Reputation: 239171

On Linux you can read and parse the nonvoluntary_ctxt_switches: line from /proc/self/status (probably best to just do a single 4096-byte read() before and after, then parse them both afterwards).

Upvotes: 5

Secto Kia
Secto Kia

Reputation: 969

In linux int getrusage(int who, struct rusage *usage); can be used to fill a struct containing timeval ru_utime (user CPU time used) and timeval ru_stime (system CPU time used), for a thread or a process.

These values along with the system clock will let you know how much CPU time your process/thread was actually running compared to how much time wasn't spent running your process/thread.

For example something like (ru_time + ru_stime) / (clock_endtime - clock_startstart) * 100 will give you CPU usage as a percent of the time elpased between start and end.

There are also some stats in there for number of context switches under certain circumstances, but that info isn't very useful.

Upvotes: 6

Related Questions