#!/bin/bash
###SHELLPACK preamble poundtime 0

###SHELLPACK parseargBegin
###SHELLPACK parseargEnd

###SHELLPACK self_extract pound_times.c 
###SHELLPACK self_extract pound_clock_gettime.c

mkdir $SHELLPACK_SOURCES/poundtime-${VERSION}-installed
for FILE in pound_times.c pound_clock_gettime.c; do
	mv $SHELLPACK_TEMP/${FILE} $SHELLPACK_SOURCES/poundtime-${VERSION}-installed/${FILE} ||
		die Failed to move ${FILE} into install directory
done

echo poundtime installed successfully
exit $SHELLPACK_SUCCESS

# Programs based on those posted to "lockless sys_times and posix_cpu_clock_get"
==== BEGIN pound_times.c ====
#include <stdio.h>
#include <pthread.h>
#include <sys/times.h>

struct tms start;

void *pound (void *threadid)
{
  struct tms end;
  int oldutime = 0;
  int utime;
  int i;
  for (i = 0; i < 5000000 / NUM_THREADS; i++) {
          times(&end);
          utime = ((int)end.tms_utime - (int)start.tms_utime);
          if (oldutime > utime) {
            printf("utime decreased, was %d, now %d!\n", oldutime, utime);
          }
          oldutime = utime;
  }
  pthread_exit(NULL);
}

int main()
{
  pthread_t th[NUM_THREADS];
  long i;
  times(&start);
  for (i = 0; i < NUM_THREADS; i++) {
    pthread_create (&th[i], NULL, pound, (void *)i);
  }
  pthread_exit(NULL);
  return 0;
}
==== END pound_times.c ====

==== BEGIN pound_clock_gettime.c ====
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>

void *pound (void *threadid)
{
	struct timespec ts;
	int rc, i;
	unsigned long prev = 0, this = 0;

	for (i = 0; i < 5000000 / NUM_THREADS; i++) {
		rc = clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts);
		if (rc < 0)
			perror("clock_gettime");
		this = (ts.tv_sec * 1000000000) + ts.tv_nsec;
		if (0 && this < prev)
			printf("%lu ns timewarp at iteration %d\n", prev - this, i);
		prev = this;
	}
	pthread_exit(NULL);
}

int main()
{
	pthread_t th[NUM_THREADS];
	long rc, i;
	pid_t pgid;

	for (i = 0; i < NUM_THREADS; i++) {
		rc = pthread_create(&th[i], NULL, pound, (void *)i);
		if (rc < 0)
			perror("pthread_create");
	}

	pthread_exit(NULL);
	return 0;
}
==== END pound_clock_gettime.c ====
