This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
Compiling c++ template is very slow.
- From: Fis Trivial <ybbs dot daans at hotmail dot com>
- To: "gcc at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>
- Date: Fri, 9 Mar 2018 02:33:40 +0000
- Subject: Compiling c++ template is very slow.
- Authentication-results: sourceware.org; auth=none
- Spamdiagnosticmetadata: NSPM
- Spamdiagnosticoutput: 1:99
I tried to use c++ template to generate code for a personal project, but
found that the compilation time needed with g++ is much
slower(exponentially) than with clang++.
This is a code snippet for testing purpose:
#include <iostream>
template <int a, int b>
struct v : v<a-1, b>, v<a, b-1>
{
static int constexpr m = a;
static int constexpr n = b;
static int constexpr s = a + b;
};
template <int b>
struct v<1, b> : v<1, b-1>
{
static int constexpr m = 1;
static int constexpr n = b;
static int constexpr s = b + 1;
};
template <int a>
struct v<a, 1> : v<a-1, 1>
{
static int constexpr m = a;
static int constexpr n = 1;
static int constexpr s = a + 1;
};
template <>
struct v<1, 1>
{
static int constexpr m = 1;
static int constexpr n = 1;
static int constexpr s = 2;
};
int main()
{
std::cout << v<7, 12>::s << std::endl;
std::cout << v<4, 3>::s << std::endl;
};
Here is the time information:
---
$ time g++ -std=c++11 generate.cc -o bygcc
real 0m39.529s
user 0m39.418s
sys 0m0.053s
$ time clang++ -std=c++11 generate.cc -o byclang
real 0m0.310s
user 0m0.273s
sys 0m0.024s
---
When using greater value, gcc will require exponentially more time to
compile while the needed time from clang grows linearly. For example,
replacing the `main` function from above code to:
int main()
{
// change 7 to 8 and drop <4, 3>
std::cout << v<8, 12>::s << std::endl;
};
---
$ time g++ -std=c++11 generate.cc -o bygcc
real 5m20.755s
user 5m8.509s
sys 0m0.260s
$ time clang++ -std=c++11 generate.cc -o byclang
real 0m0.314s
user 0m0.281s
sys 0m0.020s
---
Just for fun, making the template parameter to 128:
---
$ time g++ -std=c++11 generate.cc -o bygcc
... not gonna happen :).
$ time clang++ -std=c++11 generate.cc -o byclang
real 0m18.549s
user 0m18.410s
sys 0m0.066s
---
I am currently running Fedora 27 with following version of gcc and
clang:
$ g++ --version
g++ (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
$ clang++ --version
clang version 5.0.1 (tags/RELEASE_501/final)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /usr/bin