|
发表于 2008-6-5 00:19:49
|
显示全部楼层
好罢。经测试,偶的算法的效率素你的3倍左右~
测试素在相同情况下不打印结果计算n=32各10000次。
然后计算总时间。
结果素你的代码总时间0.4262s而偶的素0.1455s(偶的pc的执行时间)
付测试用代码。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int buffer_t[2048];
int *buf_t;
class Num{
int data[32][32];
int i,j;
int ii,jj;
public:
void fill( int n);
};
void Num::fill(int n){
i=0;
j=0;
ii=0;
jj=1;
for ( int x=0;x<32;x++){
for ( int y=0;y<32;y++){
data[x][y]=0;
}
}
for( int m=0; m<n*n; m++){
data[j]=m+1;
if ( i+ii<0 || j+jj<0 || i+ii>n-1 || j+jj>n-1 || data[i+ii][j+jj]!=0 ){
if ( ii==-1 && jj==0){
ii=0;
jj=1;
}else if ( ii==0 && jj==1){
ii=1;
jj=0;
}else if ( ii==1 && jj==0){
ii=0;
jj=-1;
}else if ( ii==0 && jj==-1){
ii=-1;
jj=0;
}
}
i+=ii;
j+=jj;
}
}
void matrix(int n){
int i,j,k=0;
for(buffer_t[0]=0,j=0;j<n;++j){
for(i=0;i<n;++i,++k){
buf_t[k]=i+j<n?i>=j?buf_t[k-1]+1:j==i+1?buf_t[k-n]+n*4-5-i*8:buf_t[k-n]-1:i>=j?buf_t[k-n]+1:buf_t[k-1]-1;
}
}
}
int main(){
Num num;
int i;
buf_t=&buffer_t[1];
LARGE_INTEGER start;
LARGE_INTEGER end;
LARGE_INTEGER frequent;
__int64 diff;
double msec;
QueryPerformanceCounter(&start);
for(i=0;i<10000;++i) num.fill(30);
QueryPerformanceCounter(&end);
diff=(__int64)end.QuadPart-(__int64)start.QuadPart;
QueryPerformanceFrequency(&frequent);
msec=(double)diff/(double)frequent.QuadPart;
printf("%f\\n",msec);
QueryPerformanceCounter(&start);
for(i=0;i<10000;++i) matrix(30);
QueryPerformanceCounter(&end);
diff=(__int64)end.QuadPart-(__int64)start.QuadPart;
QueryPerformanceFrequency(&frequent);
msec=(double)diff/(double)frequent.QuadPart;
printf("%f\\n",msec);
return 0;
} |
|