c++ - 为什么我的程序在使用 makefile 编译时变慢了?

标签 c++ makefile g++ eigen compiler-flags

tl;dr:当我以一种方式编译我的代码时,可执行文件运行很快。当我使用我的 makefile 时,它​​慢了大约 10 倍(可执行速度,不是编译时间)。

当我编译以下代码(使用 Eigen 包)时:

#include <Eigen/Dense>          // For matrix math
#include <iostream>

using namespace std;
using namespace Eigen;

// Loop an infinite number of times, computing dot products.
int main(int argc, char * argv[]) {
    setNbThreads(16);
    initParallel();     // Tell Eigen that we're going to be multithreaded.

    int n = 100;
    VectorXf a(n), b(n);
    for (int counter = 0; true; counter++) {
        a[0] = a.dot(b) / n;
        if ((counter + 1) % 10000000 == 0) {
            cout << counter / 10000000  << endl;
        }
    }
}

使用线路:

g++ *.cpp -o exe -I ./PathToEigen -std=c++11 -O2 -DNDEBUG -msse2

它运行得非常快。如果我使用下面的 makefile,生成的可执行文件会慢大约 10 倍。我做错了什么?

PROGRAM = EXE

INCLUDEDIRS = -I ./PathToEigen
CXXSOURCES = $(wildcard *.cpp)
CXXOBJECTS = $(CXXSOURCES:.cpp=.o)  # expands to list of object files
CXXFLAGS = -w $(INCLUDEDIRS)
CXX = g++

#
# Default target: the first target is the default target.
# Just type "make -f Makefile.Linux" to build it.
#

all: $(PROGRAM)

#
# Link target: automatically builds its object dependencies before
# executing its link command.
#

$(PROGRAM): $(CXXOBJECTS)
    $(CXX) -o $@ $(CXXOBJECTS) -std=c++11 -O2 -DNDEBUG -msse2

# Clean target: "make -f Makefile.Linux clean" to remove unwanted objects and executables.
#

clean:
    $(RM) -f $(CXXOBJECTS) $(PROGRAM)

#
# Run target: "make -f Makefile.Linux run" to execute the application
#             You will need to add $(VARIABLE_NAME) for any command line parameters 
#             that you defined earlier in this file.
# 

run:
    ./$(PROGRAM) 

最佳答案

因为您没有进行任何优化编译。 (CXXFLAGS中没有-O2$(PROGRAM)规则中的-O2只适用于链接步骤。)

关于c++ - 为什么我的程序在使用 makefile 编译时变慢了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20981864/

相关文章:

c++ - 使用指针时的核心转储

c++ - 如何使用 clang 和 llvm-link 链接库

qt - 如何在 qmake 和 qt5 中包含带有 -isystem(系统头文件)的 Qt 头文件?

c++ - C++ 编译器不支持 C++11(例如 std::unique_ptr)。构建 OpenWRT

c++ - "signed"关键字的实际用途是什么?

c++ - 包装正态分布 C++

c++ - RAWINPUT - 如何获取鼠标滚轮数据

c++ - 如何为资源编译器设置输出文件夹

linux - gperftools:修改 makefile 以安装在不同的文件夹中?

c++ - 使用 FLTK 和 g++ 的 undefined reference