Look at the differences between max1 and max2 2. What is the difference? 3. Do the two functions do the same amount of computation? 4. If so, do you think that the two functions will run in the same amount of time?
- Look at the differences between max1 and max2
2. What is the difference?
3. Do the two functions do the same amount of computation?
4. If so, do you think that the two functions will run in the same amount of time?
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
// For the assignment, be sure to run unmodified code, but you are free to
// play around with the code to try out different parameters or different
// implementations.
// arrs is a 16384 element array of 256 integer arrays (a 2D array)
// each function is run 50 times (numiters) in order to increase the runtime
// into the range of seconds (which is the time printed)
int max1(int** arrs, int narrs, int arrlen) {
int max = 0;
for (int i=0; i<narrs; i++) {
for (int j=0; j<arrlen; j++) {
if (arrs[i][j] > max)
max = arrs[i][j];
}
}
return max;
}
int max2(int** arrs, int narrs, int arrlen) {
int max = 0;
for (int j=0; j<arrlen; j++) {
for (int i=0; i<narrs; i++) {
if (arrs[i][j] > max)
max = arrs[i][j];
}
}
return max;
}
// This is just the main which does all of the running and printing out
// Apart from the calloc function, you should be able to understand this
// code.
int main() {
// Variables
clock_t start, end;
double seconds;
int arrlen = 256;
int narrs = 16384;
int* arrs[narrs];
for (int i=0; i < narrs; i++) {
arrs[i] = (int*)calloc(arrlen,sizeof(int));
}
int numiters = 50;
arrs[2235][34] = 1337;
int max;
// Benchmark max1
start = clock();
for (int j = 0; j < numiters; j++) {
max = max1(arrs, narrs, arrlen);
}
end = clock();
seconds = (end - start)/((double)CLOCKS_PER_SEC);
printf("max1 (%d iterations):\n", numiters);
printf("\tThe maximum value in the arrays is: %d\n", max);
printf("\ttime: %f seconds\n",seconds);
printf("\n");
// Benchmark max2
start = clock();
for (int j = 0; j < numiters; j++) {
max = max2(arrs, narrs, arrlen);
}
end = clock();
seconds = (end - start)/((double)CLOCKS_PER_SEC);
printf("max2 (%d iterations):\n", numiters);
printf("\tThe maximum value in the arrays is: %d\n", max);
printf("\ttime: %f seconds\n",seconds);
// Cleanup
for (int i=0; i < narrs; i++) {
free(arrs[i]);
}
return 0;
Trending now
This is a popular solution!
Step by step
Solved in 2 steps