/*
** CPU-bound test
*/
#include <sys/types.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <err.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
 
void runit(double y, int fd, size_t len)
{
	double  x;
	double *bp;
	size_t i;
	char	ch;
 
	bp = malloc(len);
	len /= sizeof(double);
	for (i = 0; i < len; i++)
	    bp[i] = 1.0;
	if (write(fd, "x", 1) != 1)
	    err(1, "write1");
	if (read(fd, &ch, 1) != 1)
	    err(1, "read1");
	i = 0;
	for (x = 0.0; x < y; x += 1.0) {
	    bp[i] += x;
	    if (++i >= len)
		i = 0;
	}
	exit(0);
}
 
int main(int argc, char **argv)
{
	double	y;
	pid_t p;
	int i, j, x;
	struct timeval start, end;
	struct rusage usage;
	int fds[2];
	size_t len;
	char *buf;
 
	i = strtol(argv[1], NULL, 0);
	y = strtod(argv[2], NULL);
	len = strtoul(argv[3], NULL, 0) * 1024;
 
	if (pipe(fds) < 0)
	    err(1, "pipe");
 
	buf = malloc(i);
	for (j = 0; j < i; j++) {
		p = fork();
		if (p < 0)
			err(1, "fork");
		else if (p == 0)
			runit(y, fds[1], len);
	}
	for (j = 0; j < i; j++) {
	    if (read(fds[0], buf, 1) != 1)
		err(1, "read0");
	}
	if (write(fds[0], buf, i) != i)
	    err(1, "write0");
 
	gettimeofday(&start, NULL);
	while (wait(&x) > 0)
		;
	gettimeofday(&end, NULL);
	getrusage(RUSAGE_CHILDREN, &usage);
 
	end.tv_sec -= start.tv_sec;
	end.tv_usec -= start.tv_usec;
	if (end.tv_usec < 0) {
		end.tv_usec += 1000000;
		end.tv_sec--;
	}
 
	printf("%d %g %ld.%06ld %ld.%06ld %ld.%06ld\n", i, y,
		end.tv_sec, end.tv_usec,
		usage.ru_utime.tv_sec, usage.ru_utime.tv_usec,
		usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
	return 0;
}
loop.c.txt · Last modified: 2013/06/08 11:07 by peterjeremy
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 4.0 International
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki