为什么我的程序在使用makefile编译时会变慢?

时间:2014-01-07 21:04:46

标签: 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) 

1 个答案:

答案 0 :(得分:8)

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