Files
Nils Kasulke c0a88a9f5d comment
2020-04-20 20:05:25 +02:00

109 lines
2.3 KiB
C

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
//prints out usage information
void usage();
//generate dynamically allocated array, initialized with rand()
int* rand_array(size_t n);
//converts clock ticks to nano seconds
double clocks_to_ns(double ct);
//write to /dev/null or nul
//exits if it fails
void int_to_dev_null(int trash);
//calculates the clock ticks rand() probably needs
//from a hot cache
double clock_ticks_rand();
int main(int argc, char* argv[]) {
if(argc != 4) {
usage();
return 1;
}
unsigned n_bytes;
unsigned array_size;
unsigned n_times_access;
unsigned n_loops;
sscanf(argv[1], "%u", &n_bytes);
sscanf(argv[2], "%u", &n_times_access);
sscanf(argv[3], "%u", &n_loops);
srand(time(NULL));
array_size = n_bytes / 4;
int* parry = rand_array(array_size);
clock_t start;
clock_t end;
clock_t overall = 0;
int tmp = 0;
double rc = clock_ticks_rand();
for(size_t n=0; n<n_loops; ++n) {
start = clock();
for(size_t t=0; t<n_times_access; ++t) {
//alternative way(without inner rand): tmp += parry[parry[t % array_size] % array_size];
tmp += parry[rand() % array_size];
}
end = clock();
overall += (end - start);
}
double per_instruct_ticks = overall / ((double) n_times_access * n_loops);
per_instruct_ticks = per_instruct_ticks - rc;
printf("%u, %u, %lf, %lf\n", n_bytes, array_size, clocks_to_ns(per_instruct_ticks), clocks_to_ns(rc));
int_to_dev_null(tmp);
//free not necessary
}
double clocks_to_ns(double ct) {
return ct / CLOCKS_PER_SEC * 1000000000.0;
}
void int_to_dev_null(int trash) {
#ifdef _WIN32
const char* dev_null = "nul";
#else
const char* dev_null = "/dev/null";
#endif
FILE* fnull = fopen(dev_null, "w");
if(! fnull) {
perror("unable to open /dev/null or nul");
exit(2);
}
fprintf(fnull, "%d", trash);
fclose(fnull);
}
int* array(size_t n) {
int* p=NULL;
p = malloc(sizeof(int) * n);
if(!p) {
perror("malloc failed");
exit(2);
}
return p;
}
int* rand_array(size_t n) {
int* p = array(n);
for(size_t i=0; i<n; ++i) {
p[i] = rand();
}
return p;
}
void usage() {
printf("<prog> array-size n-times-access n-loops\n");
}
double clock_ticks_rand() {
#define N 1000000
for(size_t i=0; i<N; ++i) {
rand();
}
clock_t start = clock();
for(size_t i=0; i<N; ++i) {
rand();
}
double clock_ticks_per_rand = (double)(clock() - start) / N;
return clock_ticks_per_rand;
#undef N
}