Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: C and C++ --- NPS

Author: Matt Taylor

Date: 20:15:50 12/25/02

Go up one level in this thread


On December 25, 2002 at 20:08:11, Russell Reagan wrote:

>On December 25, 2002 at 17:27:55, Peter Fendrich wrote:
>
>>What's so good with templates, regarding performance?
>
>Perhaps he means template metaprogramming. You can sometimes get an amazing
>speedups. For an example see
>http://www.tantalon.com/pete/cppopt/final.htm#TemplateMetaprogramming
>
>Russell

Interesting, but not new. I had difficulty in the past when I was trying to get
VC to generate optimized assembly output for a particular function. I would
write the function and call it from main() with a constant. The result? It would
generate a move with the evaluated result.

This doesn't happen often in large projects because the function will be in
another file, but the same principle applys for the template metaprogramming.

As for templates themselves, they have adaquate performance (better in some
cases), but I have yet to see an implementation that yields a GOOD tradeoff
between size and speed. For example, take the qsort C runtime function:

void qsort(void *base, size_t num, size_t width, int (*fncompare)(const
void *, const void *));

Can be expressed with a template as follows:

template <class T>
void qsort(T *base, size_t num);

We cut out two parameters implicit to the type -- width and fncompare. There are
two possible ways to generate code for our templated qsort function. Either the
compiler can generate the code the way the C runtime does (pass the length of
the type and comparison function as parameters), or it can generate a unique
instance for each and every type. The former choice will result in lots of code
if you call qsort with a large number of different types. The latter results in
slower code.

One other interesting problem comes into the performance vs. size tradeoff.
Small code caches more easily. Doesn't necessarily mean that a single instance
of a polymorphic routine is always preferable, but if the templates are always
expanded, you can end up losing performance and bloating your code.

Now, what I have found when I have used templates is that they work great when
you have low complexity. When you start building templates on top of templates
with nested templates (like STL), you start running into code bloat and hidden
compiler bugs. This is my experience, at least; your mileage my vary.

-Matt



This page took 0 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.