Bogomips, threads, busy-loop, spinning and other friends
Bogomips -- unscientific measurement of CPU speed made by the Linux kernel when it boots, to calibrate an internal busy-loop.
In other words ""the number of million times per second a processor can do absolutely nothing" :)
Busy waiting or spinning is a technique in which a process repeatedly checks to see if a condition is true.
I found this script on wikipedia that implements a "busy-loop" using pthread.h.
So basically a thread is waiting for another to increment the value of an integer "i", and when this happens it prints something like "i was updated, value of i is "bla...bla".
And that seemed a little bit boring so I added something of my own, the code now prints "I'm waiting" while it checks the value of "i", and the second thread increments "i" after one second.
So this extremely scientific :) test will actually benchmark your CPU too see how many prints it will do in one second.
Here's the code:
#include "stdio.h"
#include "pthread.h"
#include "unistd.h"
/* Most of this is from wikipedia */
volatile int i = 0; /* i is global, so it is visible to all functions.
It's also marked volatile, because it
will change in a way which is not predictable by the compiler
(here: from a different thread). */
/* t1 uses a spinlock to wait for i to change from 0. */
static void *f1 ()
{
printf("Starting loop\n");
while (i==0) {
printf("\tI\'m Waiting\n");
}
printf("i's value has changed to %d.\n", i);
return NULL;
}
static void *f2 ()
{
sleep(1); /* sleep for 1 second */
i = 1;
printf("t2 has changed the value of i to %d.\n", i);
return NULL;
}
int main()
{
int rc;
pthread_t t1, t2;
rc = pthread_create(&t1, NULL, f1, NULL);
if (rc != 0)
puts("pthread foo failed.");
rc = pthread_create(&t2, NULL, f2, NULL);
if (rc != 0)
puts("pthread bar failed.");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
puts("All pthreads finished.");
return 0;
}
You should compile it like this:
gcc a.c -lpthread (where a.c is the name of the file)
After compiling run the executable and redirect the output to a file, grep the file for "Waiting" and check to see how many times your PC printed "I'm Waiting" in one second while it was waiting for i to change value.
Something like this:
[root@server ~]# ./a.out > a [root@server ~]# cat a | grep Waiting | wc -l 4220456 [root@server ~]#
I should start doing something interesting with my life! :)












Comments