矩阵加法 时间性能测量

#include <stdio.h>
#include <time.h>

#define MAX_SIZE 100

typedef struct 
{
	long repetitions;
	double duration;
}times;

void timer(void (*add)( int a[][MAX_SIZE], int b[][MAX_SIZE],
		   int c[][MAX_SIZE], int n),
		   int a[][MAX_SIZE], int b[][MAX_SIZE],
		   int c[][MAX_SIZE], int n, times *x);

void add(int a[][MAX_SIZE], int b[][MAX_SIZE],
		 int c[][MAX_SIZE], int n);

		 
int main(void)
{
    static int a[MAX_SIZE][MAX_SIZE];
//    static int b[MAX_SIZE][MAX_SIZE];
    static int c[MAX_SIZE][MAX_SIZE];
    
    int k=1;
    
	times F;
    printf("function           repetitions   time");
	for(int n=20; n<=MAX_SIZE; n+=20)
	{
		k=1;
		for(int i=0; i<n; i++)
		{
			for(int j=0;j<n; j++)
		    {
		    	a[i][j]=k;
//		    	b[i][j]=k;
				k++;
		    }
		}
//		for(int i=0; i<n; i++)
//		    for(int j=0; j<n; j++)
//		        {
//		        	printf("%d ", a[i][j]);
//		    	}		
//		printf("
");
		timer(add, a, a, c, n, &F);

		printf("
F: array_size:%3d  %d    %.15lf ", n, F.repetitions, F.duration);
	}
    return 0;
}

void timer(void (*add_)( int a[][MAX_SIZE], int b[][MAX_SIZE],
		   int c[][MAX_SIZE], int n),
		   int a[][MAX_SIZE], int b[][MAX_SIZE],
		   int c[][MAX_SIZE], int n, times *x)
{
	clock_t start=clock();
	do{
		x->repetitions++;
		add_(a, b, c, n);
	}while((clock()-start)<1000);
	
	x->duration=(double)(clock()-start)/CLOCKS_PER_SEC;
	x->duration/=x->repetitions;
}

void add(int a[][MAX_SIZE], int b[][MAX_SIZE],
		 int c[][MAX_SIZE], int n)
{
	for(int i=0; i<n; i++)
		for(int j=0; j<n; j++)
		    c[i][j]=a[i][j]+b[i][j];
}

原文地址:https://www.cnblogs.com/WALLACE-S-BOOK/p/9732304.html