英文:
why program built by CMake run slower than program built by command
问题
以下是您要翻译的代码部分:
/* -*- 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);
}
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")
希望这对您有所帮助。如果您有任何其他问题,请随时提问。
英文:
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
答案1
得分: 2
您没有正确启用优化选项在您的 CMakeLists.txt
文件中。
这行代码:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O3")
将 -O3
添加到编译 C++ 文件 时传递给 g++
的参数中。但是,sieve.c
是一个 C 文件,不是 C++ 文件。
您需要设置 CMAKE_C_FLAGS
(注意是 C,而不是 CXX)来控制编译 C 文件时传递给 gcc
的参数:
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O3")
英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论