Issue
this is code below
sieve.c
/* -*- mode: c -*-
* $Id$
* http://www.bagley.org/~doug/shootout/
*/
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
#ifdef SMALL_PROBLEM_SIZE
#define LENGTH 17000
#else
#define LENGTH 170000
#endif
int NUM = ((argc == 2) ? atoi(argv[1]) : LENGTH);
static char flags[8192 + 1];
long i, k;
int count = 0;
while (NUM--) {
count = 0;
for (i=2; i <= 8192; i++) {
flags[i] = 1;
}
for (i=2; i <= 8192; i++) {
if (flags[i]) {
/* remove all multiples of prime: i */
for (k=i+i; k <= 8192; k+=i) {
flags[k] = 0;
}
count++;
}
}
}
printf("Count: %d\n", count);
return(0);
}
this is my CMakeLists.txt
cmake_minimum_required(VERSION 3.16)
project(sieve)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_C_COMPILER "gcc")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
add_executable(sieve "sieve.c")
built by CMakeLists.txt result:
time ./sieve
Count: 1028
real 0m15.436s
user 0m15.431s
sys 0m0.000s
command:
gcc sieve.c -O3 -o sieve
result:
time ./sieve
Count: 1028
real 0m3.087s
user 0m3.086s
sys 0m0.000s
Why is there such a significant difference? I would greatly appreciate it if someone could provide me with an answer.
cpu:Intel(R) Xeon(R) Platinum 8255C CPU @ 2.50GHz
OS: ubuntu22.04 LTS
Solution
You're not enabling optimizations correctly in you CMakeLists.txt
.
The line
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
adds -O3
to the arguments that are passed to g++
when compiling C++ files. But sieve.c
is a C file, not a C++ file.
You need to set CMAKE_C_FLAGS
(note: C, not CXX) to control the arguments passed to gcc
when C files get compiled:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")
Answered By - Brian61354270 Answer Checked By - Willingham (WPSolving Volunteer)