/*
 * See how fast we can send a whole pile of messages within the same task.
 *
 * Here's what I get on my system (your mileage may vary):
 *
 * 100000 round trip messages took 32.10 seconds (3115.5/s, 321us/msg)
 *
 */

#include <stdio.h>

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <signal.h>
#include <sys/time.h>

#define NUM_MSGS	100000

struct msgnode { long typ; char msg[100]; };

double
cur_time()
{
    struct timeval tv;
    gettimeofday(&tv,NULL);
    return( tv.tv_sec + tv.tv_usec / 1e6 );
}

main()
{
    int msgkey = 0xffaabb;
    int trial;
    int i, rval, msqid, msgcnt;
    long typ;
    struct msgnode msg;
    double start, end;

    msqid = msgget(msgkey, IPC_CREAT | 0777);
    if ( msqid < 0 ) {
	perror("msgget #1 failed");
	exit(1);
    }
    if ( msgctl(msqid,IPC_RMID,NULL) < 0 ) {
	perror("msgctl(IPC_RMID) failed");
	exit(1);
    }
    msqid = msgget(msgkey, IPC_CREAT | 0777);
    if ( msqid < 0 ) {
	perror("msgget #2 failed");
	exit(1);
    }

    start = cur_time();
    strcpy(msg.msg,"this is a long message to send to the other task");
    for ( i = 0; i < NUM_MSGS; i += 1 ) {
	msg.typ = 1;
	if ( msgsnd(msqid,&msg,sizeof(msg.msg),0) < 0 ) {
	    perror("msgsnd");
	    exit(1);
	}
	if ( msgrcv(msqid,&msg,sizeof(msg.msg),0,0) < 0 ) {
	    perror("msgrcv");
	    exit(1);
	}
    }
    end = cur_time();
    printf("%d round trip messages took %.2f seconds (%.1f/s, %.0fus/msg)\n",
    NUM_MSGS,end-start,NUM_MSGS / (end-start),1e6*(end-start) / NUM_MSGS);

    exit(0);
}
