#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <sys/time.h>
#include <iostream>
using namespace std;
void FlipMatrixH(int row, int col, int **matrix);
void FlipMatrixV(int row, int col, int **matrix);
int **AllocateMat(int row, int col);
void FreeArray2D(int**& array, int row);
int main(int argc, char** argv){
int row = 3200;
int col = 2400;
int REP = 101;
// initialization
int **matrix = AllocateMat(row, col);
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
matrix[i][j] = i*col+j;
}
}
// Flip the matrix vertically
timeval t_tmp;
gettimeofday(&t_tmp, NULL);
double t_start = (double)t_tmp.tv_sec + (double)t_tmp.tv_usec/1000000;
for(int i=0;i<REP;i++){
FlipMatrixV(row, col, matrix);
}
gettimeofday(&t_tmp, NULL);
double t_end = (double)t_tmp.tv_sec + (double)t_tmp.tv_usec/1000000;
printf("Time cost to flip the matrix vertically is %10.8e seconds.\n", (t_end-t_start)/REP);
// Flip the matrix horizontally
gettimeofday(&t_tmp, NULL);
t_start = (double)t_tmp.tv_sec + (double)t_tmp.tv_usec/1000000;
for(int i=0;i<REP;i++){
FlipMatrixH(row, col, matrix);
}
gettimeofday(&t_tmp, NULL);
t_end = (double)t_tmp.tv_sec + (double)t_tmp.tv_usec/1000000;
printf("Time cost to flip the matrix horizontally is %10.8e seconds.\n", (t_end-t_start)/REP);
// free
FreeArray2D(matrix, row);
}
void FlipMatrixV(int row, int col, int **matrix){
for(int j=0; j<col; j++){
for(int i=0;i<row/2;i++){
int temp = matrix[i][j];
matrix[i][j] = matrix[row-i-1][j];
matrix[row-i-1][j] = temp;
}
}
}
void FlipMatrixH(int row, int col, int **matrix){
for(int i=0;i<row;i++){
for(int j=0;j<col/2;j++){
int temp = matrix[i][j];
matrix[i][j] = matrix[i][col-1-j];
matrix[i][col-1-j] = temp;
}
}
}
int **AllocateMat(int row, int col){
int **array=NULL;
try{
array = new int*[row];
for(int i=0;i<row;++i)
array[i]=new int[col];
}catch(...){
std::cerr<<"Error: Can't allocate mem!"<<std::endl;
exit(1);
}
return array;
}
void FreeArray2D(int**& array, int row){
if(array){
for(int i=0;i<row;++i)
if(array[i])
delete [] array[i];
delete []array;
array=NULL;
}
}