Jump to content

C program which measures the the speed of a context switch on a UNIX/Linux

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Roger

Roger

    If nothing goes right, go left.

  • Administrators
  • 718 posts
  • Programming Language:C, PHP
  • Learning:Python
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!
Check out our update Guidelines/FAQ. When posting code, remember to use code tags - Posted Image.

#2
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
  • Location:Vancouver, Eh! Cleverness: 200
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.

#3
Roger

Roger

    If nothing goes right, go left.

  • Administrators
  • 718 posts
  • Programming Language:C, PHP
  • Learning:Python
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 - Posted Image.




2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users