Author: Dann Corbit
Date: 18:30:52 02/05/02
Go up one level in this thread
On February 05, 2002 at 21:13:20, Pham Minh Tri wrote: >Note that his question is "without using none kind of loops" so struct >assignment and memcpy are surely not answer because they use some assembly loop >;) > >I think even they are the fastest solutions for his problem but the answer for >that question is switch statement. I doubt it. Switch is a construct you should use only if you have to[1]. And if that particular area is a bottleneck, I doubt very much if it will help. A mispredicted branch is one of the worst things that can go wrong on a modern CPU, and switch statements are mis-predicted branch generators. [1] I am talking about performance solutions here. If a switch is clearest, write using a switch. But if you have a slow spot, it is probably not going to help to change to a switch. Try this on your handy-dandy compiler and tell me how it turns out: #include <math.h> #include <stdio.h> typedef double (*f_t) (double); static f_t f[] = {log, log10, sqrt, cos, cosh, exp, sin, sinh, tan, tanh, 0}; static double accum0 = 0; static double accum1 = 0; static double accum2 = 0; void arr(void) { int i; double d = 0; for (i = 0; f[i]; i++) { d += f[i] (0.5); } accum0 += d; } void poi(void) { f_t *flist = f; double d = 0; while (*flist) { f_t ff = *flist; d += ff(0.5); flist++; } accum1 += d; } void swi(void) { int i; double d = 0; for (i = 0; f[i]; i++) { switch (i) { case 0: d += f[0] (0.5); break; case 1: d += f[1] (0.5); break; case 2: d += f[2] (0.5); break; case 3: d += f[3] (0.5); break; case 4: d += f[4] (0.5); break; case 5: d += f[5] (0.5); break; case 6: d += f[6] (0.5); break; case 7: d += f[7] (0.5); break; case 8: d += f[8] (0.5); break; case 9: d += f[9] (0.5); break; default: break; } } accum2 += d; } int main(void) { long i; for (i = 0; i < 1000000; i++) { arr(); poi(); swi(); } printf("%.20g, %.20g, %.20g\n", accum0, accum1, accum2); return 0; }
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.