Here is my code:
Code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <time.h>
#define NSEMS 2
/* change this per CPU to run between 8 and 12 s*/
const static int maxloop = 10000000;
main(int argc, char *argv[])
{
time_t start,last,stop;
long int i;
int estimate = 100;
int sid;
key_t key;
ushort vals[NSEMS] = { 0, 0 };
key = ftok("/tmp",99);
last=start=time(NULL);
for (i = 0; i < 1000; ++i) {
usleep(10);
last=time(NULL);
if (last > start) break;
}
start=last;
last = 0;
for (i = maxloop/8; i < maxloop; i++) {
if ((sid = semget(key, NSEMS, IPC_CREAT | 0777)) == -1) {
perror("Can Not Get Semaphore ID");
}
if (semctl(sid, NSEMS, GETALL, vals) == -1) {
perror("Can Not Get Semaphore Values");
}
}
/* do the last 1/8th until the second changes.
If your processor reaches the maxloop before that,
change the maxloop or the divisor or the "estimate" */
stop=time(NULL);
for (i = maxloop - maxloop/8; i < maxloop; ++i) {
if ( !(i % estimate) ) {
last=time(NULL);
if (last > stop) break;
stop=last;
}
/* repeat semaphore opts */
if ((sid = semget(key, NSEMS, IPC_CREAT | 0777)) == -1) {
perror("Can Not Get Semaphore ID");
}
if (semctl(sid, NSEMS, GETALL, vals) == -1) {
perror("Can Not Get Semaphore Values");
}
}
stop=last;
printf("%.2f semop/s (%i/%i) [%d]\n", (double)i/(stop-start), i, stop-start, estimate);
}