下面求助测量矩阵乘法的执行时间。我在 Windows 中运行代码。我尝试使用 time.h , 但无法测量。我必须把计时器放在哪里?
#include<stdio.h>
#include<math.h>
#include<time.h>
void main()
{
int m1[10][10],i,j,k,m2[10][10],add[10][10],mult[10][10],r1,c1,r2,c2;
/*double dif;
time_t start, end;*/
printf("Enter number of rows and columns of first matrix MAX 10\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of second matrix MAX 10\n");
scanf("%d%d",&r2,&c2);
if(r2==c1)
{
printf("Enter rows and columns of First matrix \n");
printf("Row wise\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
scanf("%d",&m1[i][j]);
}
printf("You have entered the first matrix as follows:\n");
for(i=0;i<r1;i++)
{
for(j=0;j<c1;j++)
printf("%d\t",m1[i][j]);
printf("\n");
}
printf("Enter rows and columns of Second matrix \n");
printf("Again row wise\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
scanf("%d",&m2[i][j]);
}
printf("You have entered the second matrix as follows:\n");
for(i=0;i<r2;i++)
{
for(j=0;j<c2;j++)
printf("%d\t",m2[i][j]);
printf("\n");
}
/*time (&start);*/
printf("Now we multiply both the above matrix \n");
printf("The result of the multiplication is as follows:\n");
/*a11xA11+a12xA21+a13xA31 a11xA12+a12xA22+a13xA32 a11xA13+a12xA23+a13xA33*/
for(i=0;i<r1;i++)
{
for(j=0;j<c2;j++)
{
mult[i][j]=0;
for(k=0;k<r1;k++)
{
mult[i][j]+=m1[i][k]*m2[k][j];
/*mult[0][0]=m1[0][0]*m2[0][0]+m1[0][1]*m2[1][0]+m1[0][2]*m2[2][0];*/
}
printf("%d\t",mult[i][j]);
}
printf("\n");
/*time (&end);
dif (difftime (end, start);
printf("Time of execution is : %f\n",dif)*/
}
getch();
}
else
{
printf("Matrix multiplication cannot be done");
}
}
我希望测量尽可能准确。
最佳答案
我认为您最好在调用 getch()
之前立即使用当前循环之外的“结束时间”代码。这将为您提供超过 1 秒计数的最大机会。为了获得合适的度量,您可能需要多次重复整个乘法(以便以 10 秒为单位测量总耗用时间)。您也应该避免在循环中打印;打印时间可能会主导计算时间。
剩下的麻烦是 time()
系统调用提供了 1 秒的时间分辨率。您确实需要一个具有亚秒分辨率的计时程序,例如 gettimeofday()
(微秒)或 clock_gettime()
(纳秒)。请注意,分辨率和精度是不同的。 (您可以改用 clock()
,它是标准 C,但通常提供的分辨率要低得多。历史上,还有 ftime()
和 times()
可以使用. These gave millisecond resolution.) Windows 上还有其他可用的系统调用。您仍然需要大量重复计数以使计时有用(1000 次、10,000 次或 1,000,000 次),因为执行 10x10 矩阵乘法不需要很长时间。
关于c - 如何在C中对矩阵乘法进行计时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10779684/