c - 创建单位矩阵时出现性能异常

标签 c matrix performance-testing memset

首先,抱歉我的英语很糟糕。

我编写了一个程序,用于寻找在函数中动态创建单位矩阵的最佳方法。我有三个用于创建单位矩阵的函数。第一个功能和第二个功能几乎相同。它们之间的唯一区别是:第一个函数使用 memset 函数用零填充数组,第二个函数内置此功能。最后一个函数使用条件语句使所有内容仅在一个循环中进行。我认为使用条件语句会不必要地减慢函数的速度。

代码的性能比较结果很有趣,与我的所有猜测相反:

1: 1194 
2: 551 
3: 440 

最后一个使用条件语句的函数如何比其他函数更快? memset 是一个开发了很长时间的函数,它怎么会比我的内置代码慢?

来源:

#include <stdio.h>
#include <string.h>

#include <time.h>

typedef float MAT4[4][4];

void identityMatrix_1(MAT4 matrix)
{
    memset(matrix, 0, sizeof(matrix[0][0]) * 4 * 4);

    for(int I = 0; I < 4; I++)
    {
        matrix[I][I] = 1;
    }
}

void identityMatrix_2(MAT4 matrix)
{
    for(int X = 0; X < 4; X++)
    {
        for(int Y = 0; Y < 4; Y++)
        {   
            matrix[X][Y] = 0;
        }
    }

    for(int I = 0; I < 4; I++)
    {
        matrix[I][I] = 1;
    }
}

void identityMatrix_3(MAT4 matrix)
{
    for(int X = 0; X < 4; X++)
    {
        for(int Y = 0; Y < 4; Y++)
        {   
            if(X == Y)
            {
                matrix[X][Y] = 1;
            }
            else
            {       
                matrix[X][Y] = 0;
            }       
        }
    }

}

void printMAT4(MAT4 matrix)
{
    for(int X = 0; X < 4; X++)
    {
        for(int Y = 0; Y < 4; Y++)
        {   
            printf("%f ",matrix[X][Y]);
        }
        printf("\n");
    }
}

clock_t startTime, endTime;

int main(void) {
    MAT4 i1, i2, i3;

    startTime = clock();
    for(int I = 0; I < 10000; I++)
        identityMatrix_1(i1);
    endTime = clock();

    printf("1: %li \n", endTime - startTime);

    startTime = clock();
    for(int I = 0; I < 10000; I++)
        identityMatrix_2(i2);
    endTime = clock();

    printf("2: %li \n", endTime - startTime);

    startTime = clock();
    for(int I = 0; I < 10000; I++)
        identityMatrix_3(i3);
    endTime = clock();

    printf("3: %li \n", endTime - startTime);


//for optimizing the code correctly.
printMAT4(i1);
printMAT4(i2);
printMAT4(i3);

    return 0;
}

编辑:我不优化该程序。

编辑:我根据答案编辑了程序并优化了程序。

优化结果 (-O3):

1: 188 
2: 0 
3: 0 

最佳答案

如果您在打开优化的情况下编译此文件,编译器可能会注意到您从未从矩阵中读取数据,因此仅删除 IdentityMatrix 函数是有效的。

如果您没有在关闭优化的情况下进行编译,编译器将不会优化您的函数,因此您将获得计时,但它们毫无意义,因为它们与打开优化时获得的结果有很大不同。

关于c - 创建单位矩阵时出现性能异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39680570/

相关文章:

c - 将输入文件标记为链表

c - 在二维矩阵中向右移动部件

python - python 为什么比 C 和 C++ 运行得更快?

使用 JSR223 - 0 和空响应而不是实际值的 JMeter 请求

c - 如何将 uint8_t 数组与 C 中的字符串进行比较?

c - 如何制作一个可以在不同代码库中重用的C "library"?

c++ - 如何在 C++ 中通过引用传递堆栈矩阵

mysql - 如何在 JMeter 中通过 JDBC 采样器运行多个 MySQL 语句

c - 需要创建一个函数来调用另一个函数

android - 旋转后的 OpenGL ES 2 翻译