I have this timeissorted.c file, and right now it's running at around about 8397599 usec. I'm looking for help toward improving the performance of this code to make it run faster.
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <stdlib.h>
static struct timeval start_ts, end_ts, diff_ts;
void startClock() {
gettimeofday(&start_ts, 0);
}
void endClock() {
gettimeofday(&end_ts, 0);
}
struct timeval timeminus(struct timeval a, struct timeval b)
{
struct timeval res;
res.tv_sec = a.tv_sec - b.tv_sec;
if (a.tv_usec > b.tv_usec) {
res.tv_usec = a.tv_usec - b.tv_usec;
} else {
res.tv_usec = 1000000 + a.tv_usec - b.tv_usec;
res.tv_sec--;
}
return res;
}
long usecClock() {
diff_ts = timeminus(end_ts, start_ts);
return diff_ts.tv_usec + 1000000 * diff_ts.tv_sec;
}
int longLess(const void *a, const void *b) {
return *(long *)a - *(long *)b;
}
extern int issorted(long *p, long n);
int main(int argc, char **argv)
{
long l, limit = 500000, size = 10000;
long *p = calloc(size, sizeof(long));
long x;
for (l = 0; l < size; ++l) {
p[l] = random() % size;
}
qsort(p, size, sizeof(long), longLess);
p[0] = size + 1;
if (issorted(p, size))
printf("Got the wrong answer\n");
qsort(p, size, sizeof(long), longLess);
p[size - 1] = -1;
if (issorted(p, size))
printf("Got the wrong answer\n");
qsort(p, size, sizeof(long), longLess);
p[size / 2] = size + 1;
if (issorted(p, size))
printf("Got the wrong answer\n");
qsort(p, size, sizeof(long), longLess);
printf("Timing issorted\n");
x = 1;
startClock();
for (l = 0; l < limit; ++l) {
x &= issorted(p, size);
}
endClock();
if (!x)
printf("Got the wrong answer\n");
printf("%ld invocations of issorted(%ld) took: %ld usec\n", limit, size, usecClock());
return 0;
}