2

I wonder if anyone of you know how to to use the function get_timer() to measure the time for context switch

how to find the average? when to display it?

Could someone help me out with this.

Is it any expert who knows this?

soker
  • 21
  • 1
  • 3
  • It would probably help if you added a tag specifying *what* kernel you're talking about/interested in (e.g., Linux, OSX/Darwin, Windows, etc.) – Jerry Coffin Sep 18 '11 at 16:18
  • 1
    possible duplicate of [Write a C program to measure time spent in context switch in Linux OS](http://stackoverflow.com/questions/2368384/write-a-c-program-to-measure-time-spent-in-context-switch-in-linux-os) – Karoly Horvath Sep 18 '11 at 16:22
  • @Jerry Coffin It is a Linux kernel – soker Sep 18 '11 at 16:30

3 Answers3

5

One fairly straightforward way would be to have two threads communicating through a pipe. One thread would do (pseudo-code):

for(n = 1000; n--;) {
    now = clock_gettime(CLOCK_MONOTONIC_RAW);
    write(pipe, now);
    sleep(1msec); // to make sure that the other thread blocks again on pipe read
}

Another thread would do:

context_switch_times[1000];
while(n = 1000; n--;) {
    time = read(pipe);
    now = clock_gettime(CLOCK_MONOTONIC_RAW);
    context_switch_times[n] = now - time;
}

That is, it would measure the time duration between when the data was written into the pipe by one thread and the time when the other thread woke up and read that data. A histogram of context_switch_times array would show the distribution of context switch times.

The times would include the overhead of pipe read and write and getting the time, however, it gives a good sense of big the context switch times are.

In the past I did a similar test using stock Fedora 13 kernel and real-time FIFO threads. The minimum context switch times I got were around 4-5 usec.

Maxim Egorushkin
  • 131,725
  • 17
  • 180
  • 271
3

I dont think we can actually measure this time from User space, as in kernel you never know when your process is picked up after its time slice expires. So whatever you get in userspace includes scheduling delays as well. However, from user space you can get closer measurement but not exact always. Even a jiffy delay matters.

Gyan Gupta
  • 986
  • 8
  • 15
1

I believe LTTng can be used to capture detailed traces of context switch timings, among other things.

bdonlan
  • 224,562
  • 31
  • 268
  • 324