WordCount performance

Daniel murpsoft at hotmail.com
Wed Mar 26 20:14:12 PDT 2008


bearophile Wrote:

> The following little program comes from a progressive stripping down of a program I was creating. This C and D code give the approximate count of the words in a file:
> 
> D version:
> 
> import std.c.stdio: printf, getchar, EOF;
> import std.ctype: isspace;
> 
> void main() {
>     int count, c;
> 
>   //OUTER:
>     while (1) {
>         while (1) {
>             c = getchar();
>             if (c == EOF)
>                 //break OUTER;
>                 goto END;
>             if (!isspace(c))
>                 break;
>         }
> 
>         count++;
> 
>         while (1) {
>             c = getchar();
>             if (c == EOF)
>                 //break OUTER;
>                 goto END;
>             if (isspace(c))
>                 break;
>         }
>     }
> 
>   END:
>     printf("%d\n", count);
> }
> 
> 
> C version:
> 
> #include <stdio.h>
> #include <ctype.h>
> 
> int main() {
>     int count = 0, c;
> 
>     while (1) {
>         while (1) {
>             c = getchar();
>             if (c == EOF)
>                 goto END;
>             if (!isspace(c))
>                 break;
>         }
> 
>         count++;
> 
>         while (1) {
>             c = getchar();
>             if (c == EOF)
>                 goto END;
>             if (isspace(c))
>                 break;
>         }
>     }
> 
>     END:
>     printf("%d\n", count);
>     return 0;
> }
> [snip]

As an exercise for the viewer, if you use SSE2, prefetch, and non-branching bitmath you can perform this roughly 32 times as fast.

Regards,
Daniel



More information about the Digitalmars-d mailing list