通过添加操作来优化特征表达

时间:2019-02-25 13:00:42

标签: c++ optimization eigen eigen3

在我的机器MSVC(内置发行版)中,以下代码中的计算1比计算2快得多(6s对8.5s)。为什么会这样?

这是完整的代码(main.cpp):

#include <Eigen/Dense>
#include <chrono>
#include <iostream>

using namespace std;
using namespace Eigen;

int main()
{
    Matrix3Xf a = Matrix3Xf::Random(3, 400);
    Vector3f v = Vector3f::Random();
    RowVectorXf b = RowVectorXf::Random(400);

    auto start = chrono::steady_clock::now();

    for (float f = 0; f < 1000000; f++)
    {
        // calculation 1:
        //b.noalias() += (v.transpose() * (a * 1));

        // calculation 2:
        b.noalias() += (v.transpose() * a);
    }

    auto end = chrono::steady_clock::now();

    cout << "Elapsed time in milliseconds : "
        << chrono::duration_cast<chrono::milliseconds>(end - start).count()
        << " ms" << endl;

    getchar();

    return 0;
}

这是要复制的CMakeLists.txt

cmake_minimum_required(VERSION 3.1)
project(testProject)

# Set a default build type if none was specified
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
    message(STATUS "Setting build type to 'Release' as none was specified.")
    set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build." FORCE)
    # Set the possible values of build type for cmake-gui
    set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
        "MinSizeRel" "RelWithDebInfo")
endif()

find_package(Eigen3 3.3.7 NO_MODULE)

set(SOURCES main.cpp )

add_executable(testProject ${SOURCES} ${SOURCES_test})

target_link_libraries (testProject PUBLIC Eigen3::Eigen)

0 个答案:

没有答案