Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22031

Why does this code take so long to compile with g++?

$
0
0

Consider the following code:

template<int i> class A
{
    typedef A<i-1> B;
    B x, y;
};
template<> class A<0> { char m; };
int main()
{
    A<LEVEL> a;
}

When benchmarking its compilation by g++ by the following Bash command (with g++ 8.3.0)

for ((level=1; level<30; ++level)); do
    echo -n ${level},
    /usr/bin/time -f %U g++ -DLEVEL=$level test.cpp -o /dev/null
done

I get the following output:

1,0.03
2,0.03
3,0.04
4,0.04
5,0.04
6,0.04
7,0.04
8,0.04
9,0.03
10,0.04
11,0.02
12,0.04
13,0.02
14,0.03
15,0.04
16,0.05
17,0.05
18,0.08
19,0.11
20,0.20
21,0.35
22,0.67
23,1.30
24,2.52
25,5.02
26,10.23
27,19.96
28,40.30
29,80.99

So, compilation time is exponential in LEVEL. But if I change B x, y; to B x[2];, then compilation happens in constant time (~30 ms).

Why does it happen? I thought that, since the compiler knows that B is one and the same type for both x and y, it would take the same time as compiling x[2]. But for some reason it appears different. Can I somehow force B to be realized (as opposed to simply aliased) so that g++ could create both variables just as easily as it created the array?


Viewing all articles
Browse latest Browse all 22031

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>