矩阵转置函数时间性能测量(最差情形)

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

#define MAX_SIZE 100

#define SWAP(x, y, t) ((t)=(x), (x)=(y),(y)=t)

void transpose(int a[][MAX_SIZE],int n);

int main(void)
{
	int step=10;
	double duration;
	clock_t start;
	long repetitions;
	int num=1,k=0;
			
	int a[MAX_SIZE][MAX_SIZE];
	printf("     n    time
");
	for(int n=0; n<=100; n+=step)
	{
		repetitions=0;
		num=1;
		for(int i=0; i<n; i++)
		{
			for(int j=0;j<n; j++)
		    {
		    	a[i][j]=num;
		    	num++;
				k++;
		    }
		}
		start=clock();
		do{
			repetitions++;
			transpose(a, n);
		}while((clock()-start)<1000);
		//printf("%f %f", (double)start,(double)clock());
		
		duration=((double)(clock()-start)/CLOCKS_PER_SEC);
		duration/=repetitions;
		
		printf("%6d   %ld   %.15lf   %d
", n*n, repetitions, duration, k);

//		for(int i=0;i<n;i++)
//			for(int j=0;j<n; j++)
//			    printf("%d ", a[i][j]);
//
//		putchar('
');
//		if(n==100) 
//		   step=100;
	}
	return 0;
}

void transpose(int a[][MAX_SIZE],int n)
{
	int i,j,temp;
	for(i=0; i<n; i++)  
	{   
		for(j=i+1; j<n; j++) 
		{
			SWAP(a[i][j], a[j][i], temp);
		}
	}
}

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