How would you write a C program that measures the speed of a context switch on a UNIX/Linux system?
I'm preparing for an interview with Google next week. Although the job will be more Product-related vs. Programming, I am still doing some research to see what type of programming questions they'll ask. I'll post a couple more to see if you can help me out.
Thanks!
C program which measures the the speed of a context switch on a UNIX/Linux
Started by Roger, Aug 22 2010 12:49 PM
2 replies to this topic
#1
Posted 22 August 2010 - 12:49 PM
Check out our update Guidelines/FAQ. When posting code, remember to use code tags -
.
.
|
|
|
#2
Posted 22 August 2010 - 09:15 PM
Ah, UNIX stuff. Essentially you would create a function to alternate between persistant thread states, set lock and start/wakeup/sleep conditions plus a counter.
uint32_t COUNTER;
pthread_mutex_t LOCK;
pthread_mutex_t START;
pthread_cond_t CONDITION;
void * threads (void * unused) {
pthread_mutex_lock(&START);
pthread_mutex_unlock(&START);
pthread_mutex_lock(&LOCK);
if (COUNTER > 0) {
pthread_cond_signal(&CONDITION);
}
for (;;) {
COUNTER++;
pthread_cond_wait(&CONDITION, &LOCK);
pthread_cond_signal(&CONDITION);
}
pthread_mutex_unlock(&LOCK);
}Next we create persistant threads t1 and t2 which are unlocked (awoken), and we roughly sleep one second to let them do their firing. (rough approximate of one second, granularity is different among platforms/clocks) pthread_mutex_lock(&START);
COUNTER = 0;
pthread_create(&t1, NULL, threads, NULL);
pthread_create(&t2, NULL, threads, NULL);
pthread_detach(t1);
pthread_detach(t2);
myTime = tTimer();
pthread_mutex_unlock(&START);
sleep(1);
// Lock both simulaneous threads
pthread_mutex_lock(&LOCK);
//Normalize the result in second precision
myTime = tTimer() - myTime / 1000;On my system I get the result of 193349 switches per second. I omitted some initialization/timer function for the sake of explaining the most important parts.
Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.
#3
Posted 22 August 2010 - 10:47 PM
whoa, you're fast man.. thanks, I'll need some time to digest this.. it's been a while since my last C program.. :)
Check out our update Guidelines/FAQ. When posting code, remember to use code tags -
.
.
2 user(s) are reading this topic
0 members, 2 guests, 0 anonymous users


Sign In
Create Account

Back to top









