【发布时间】:2017-06-11 15:46:56
【问题描述】:
我正在编写简单的程序,我想测量它在 Windows 和 Linux(均为 64 位)上的执行时间。我有一个问题,因为在 Windows 上表中的 1 000 000 个元素大约需要 35 秒,而在 linux 上,10 个元素大约需要 30 秒。为什么差异如此之大? 我究竟做错了什么?我的代码中有什么东西在 Linux 上不合适吗?
这是我的代码:
void fillTable(int s, int t[])
{
srand(time(0));
for (int i = 0; i < s; i++)
{
t[i] = rand();
}
}
void checkIfIsPrimeNotParalleled(int size, int table[])
{
for (int i = 0; i < size; i++)
{
int tmp = table[i];
if (tmp < 2)
{
}
for (int i = 2; i < tmp; i++)
{
if (tmp % i == 0)
{
}
else
{
}
}
}
}
void mesureTime(int size, int table[], int numberOfRepetitions)
{
long long sum = 0;
clock_t start_time, end_time;
fillTable(size, table);
for (int i = 0; i < numberOfRepetitions; i++)
{
start_time = clock();
checkIfIsPrimeNotParalleled(size, table);
end_time = clock();
double duration = (end_time - start_time) / CLOCKS_PER_SEC;
sum += duration;
}
cout << "Avg: " << round(sum / numberOfRepetitions) << " s"<<endl;
}
int main()
{
static constexpr int size = 1000000;
int *table = new int[size];
int numberOfRepetitions = 1;
mesureTime(size, table, numberOfRepetitions);
delete[] table;
return 0;
}
和 Linux 的 makefile。在 Windows 上,我使用的是 Visual Studio 2015
.PHONY: Project1
CXX = g++
EXEC = tablut
LDFLAGS = -fopenmp
CXXFLAGS = -std=c++11 -Wall -Wextra -fopenmp -m64
SRC= Project1.cpp
OBJ= $(SRC:.cpp=.o)
all: $(EXEC)
tablut: $(OBJ)
$(CXX) -o tablut $(OBJ) $(LDFLAGS)
%.o: %.cpp
$(CXX) -o $@ -c $< $(CXXFLAGS)
clean:
rm -rf *.o
mrproper: clean
rm -rf tablut
主要目标是测量时间。
【问题讨论】:
-
有什么理由不让 GCC 优化这段代码? (喜欢 -03 选项?)
-
你是在Windows下以Release模式运行代码吗?
-
当我用 O3、O2 甚至 O1 运行这个项目时,99999999 个元素的时间是 0 秒
-
你的被测函数没有效果,对函数的调用可以优化掉。
-
微基准测试比仅仅围绕某个函数循环要难一些。例如,请参阅 Chandler Carruth 在 youtube 上的演讲。