Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jlebar
Last active December 16, 2015 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jlebar/5367521 to your computer and use it in GitHub Desktop.
Save jlebar/5367521 to your computer and use it in GitHub Desktop.
Spawns one thread, then does a series of computations on the main thread and on the spawned thread. Periodically outputs the speed of those two computations.
// Compile me with -lrt -lpthread -lm.
//
// To force this program to run on one core, use |taskset 1|.
//
// See post on http://jlebar.com for why this is relevant.
#include <pthread.h>
#include <math.h>
#include <stdio.h>
#include <unistd.h>
#include <time.h>
#include <sys/syscall.h>
// sigh, glibc does not provide this.
int gettid()
{
return syscall(SYS_gettid);
}
double GetTimeSec()
{
struct timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
return tp.tv_sec + tp.tv_nsec * 1e-9;
}
void* Spin(void*)
{
printf("tid %d spinning...\n", gettid());
double v = 0;
double lastTime = GetTimeSec();
while (true) {
for (double i = 1; i < 10000000; i++) {
// Do something hard that can't be optimized out.
v += tan(cos(sin(i)));
}
double now = GetTimeSec();
printf("tid %d: Finished iteration in %0.2fs\n", gettid(), now - lastTime);
lastTime = now;
// Use v so the compiler can't optimize it out. In other news, GCC is
// smart enough to know that printf("") is a nop!
if (v == 0) {
printf(" ");
}
}
return NULL;
}
int main(int, const char**)
{
pthread_t thread;
pthread_create(&thread, NULL, Spin, NULL);
Spin(NULL);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment