Create a gist now

Instantly share code, notes, and snippets.

@jlebar /gist:5367521
Last active Dec 16, 2015

What would you like to do?
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