[Skip Header and Navigation] [Jump to Main Content]
bobah.net
details matter

Primary Links

  • Success Story
  • D4D
  • Tools
  • Source Code
    • Copyright & License
    • Math
    • Networking
    • Miscelanea
      • Java Glob Pattern Matcher
      • Log4j Configuration and Usage
      • Context Switch Benchmark (POSIX, C++)
      • Advanced EasyMock Usecases
      • Dependency Injection in C++
      • Java AVL Tree
      • Message Queue Event Loop Example (J2SE)
      • Thread Pool Executor Example (J2SE)
      • invokevirtual vs invokeinterface performance benchmark
  • Process
  • Raspberry Pi
  • Unix
Home » Developer for Developers » Source Code » Miscelanea

Context Switch Benchmark (POSIX, C++)

Submitted by bobah on May 2, 2010 - 15:43
Sample code for context switching speed benchmarking on POSIX (pthreads, tested on Linux). The code also demonstrates how alarm signal can be used for printing regular stats.
#include <sched.h>
#include <sys/time.h>
#include <signal.h>
#include <pthread.h>

#include <cstdint>
#include <cstdlib>

#include <iostream>


#define NUM_THREADS 20


namespace {

pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

volatile long switches = 0L;
long msec = 0L;

/**
 * Current GMT time in ms since the Epoch
 */
uint64_t epochmsec() {
 timeval tv = timeval();
 if (gettimeofday(&tv, 0) == 0) {
   return tv.tv_sec * 1000 + tv.tv_usec / 1000;
 }
 else {
   return 0L;
 }
}

/**
 * ALRM signal handler, logs context switching statistics
 */
void alarm_handler(int signum) {
 alarm(1);
 uint64_t tm = epochmsec();
 uint64_t delta = tm - msec;
 msec = tm;
 std::cout << (delta / (double) switches * 1000) << "us" << std::endl;
 switches = 0;
}

/**
 * Thread function
 */
void* thread_func(void* arg) {
 for(;;) {
   pthread_mutex_lock(&mtx);
   ++switches;
   pthread_mutex_unlock(&mtx);
   sched_yield();
 }
}

} // namespace

int main() {
 msec = epochmsec();

 pthread_t threads[NUM_THREADS];

 for (size_t i = 0; i < sizeof(threads) / sizeof(pthread_t); ++i) {
   pthread_create(&threads[i], 0, &thread_func, 0);
 }

 // setup an alarm to print log message every second
 signal(SIGALRM, &alarm_handler);
 alarm(1);

 for (;;) {
   sleep(1000);
 }

 return 0;
}
‹ Log4j Configuration and Usage up Advanced EasyMock Usecases ›
  • Printer-friendly version
  • Add new comment

Measurements

Submitted by bobah on May 15, 2010 - 15:53.

On the test Linux box (Quad Core Q6600) the average context switch time is 0.9us (20 threads)

  • reply
© 2008—2011 bobah.net
[Jump to Top] [Jump to Main Content]