#include #include #include #include /* The iteration count below needs to be in a reasonable range for the specific hardware this program is run on. If you make a change to the inner loop that makes it slower (as assigned in the lab), you may also want to adjust the iteration count downward. */ #define ITERATIONS 1000000 /* This program runs furiously away in a loop, writing a character to a temporary file each time around the loop. It will stop only when interrupted or killed. Every ITERATIONS times through its loop it prints a report of how long (in microseconds) it took to do the last ITERATIONS iterations. The time is elapsed (wall clock) time, so that it includes not only time this process spent, but also time when the processor is busy running other processes. The times are not actually accurate to the microsecond. -Max Hailperin 1999-08-30 */ int main(int argc, char *argv[]){ FILE *outFile; /* temporary output file, as high-level FILE* */ int outFd; /* same, but as low level file descriptor */ if((outFile = tmpfile()) == NULL){ fprintf(stderr, "Couldn't open temporary file.\n"); exit(1); } outFd = fileno(outFile); /* convert to system-level file desciptor */ while(1){ /* Do the timing test repeatedly until killed. */ struct timeval start, stop; long diff, i; char c = 'X'; /* arbitrary character to write. */ if(gettimeofday(&start, 0) < 0){ /* Get starting time. */ perror("gettimeofday"); exit(1); } for(i = ITERATIONS; i > 0; i--){ /* the actual test */ if(write(outFd, &c, 1) < 0){ /* write the 'X' out from c to temp file */ perror("write"); } /* The above write not only outputs the character, but also advances the file position by one byte. Thus if repeated, we would wind up with a very long file of Xs, and chew up the disk. So to avoid that, we want to back up and do the next X on top of this one. The lseek system call below does this, by setting the file position back to the beginning. */ if(lseek(outFd, 0, SEEK_SET) < 0){ perror("lseek"); } } if(gettimeofday(&stop, 0) < 0){ /* Get ending time. */ perror("gettimeofday"); exit(1); } diff = stop.tv_sec - start.tv_sec; diff *= 1000000; /* microseconds per second */ diff += stop.tv_usec - start.tv_usec; printf("%ld\n", diff); /* Print elapsed time. */ } }