我正在編寫簡單的程序,我想在Windows和Linux(都是64)上執行它的執行時間。我遇到了一個問題,因爲在Windows桌面上的1 000 000個元素大約需要35秒,而在Linux上,10個元素需要大約30秒。爲什麼差異如此巨大? 我在做什麼錯?我的代碼中有什麼不適合在Linux上?在Linux上的C++代碼比在Windows上慢很多
這裏是我的代碼:
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 [email protected] -c $< $(CXXFLAGS)
clean:
rm -rf *.o
mrproper: clean
rm -rf tablut
主要目標是確定時間。
你不讓GCC優化此代碼的任何原因? (如-03選項?) – JVApen
您是否在Windows下以發行模式運行代碼? – Rakete1111
當我使用O3,O2甚至O1運行此項目時,99999999元素的時間爲0秒 – karo96