in reply to Preprocessor Pranks

  1. Which is faster, preprocessor (-P) or use constant pragma?
    They both are the same.

  2. How did you find this out (better yet, aside from reading the internals of the perl interpreter -- I am not ready, is there a way to profile the compilation stage and where can I go to read/learn about such things)?
    You can use the B::Graph module to see how perl constructed the execution tree for the code you've written. The only difference between the two is that when you use constant, the constant needs to be initialized at the top of the parse tree, while the preprocessed code does not have such step.

  3. Once the optimizer strips out unnecessary code, at anytime in recompilation (such as when an eval() gets compiled at run-time), does this folded code effect the compilation time?
    I believe once a portion of code is discarded, it is discarded forever. In the example above, since you cannot change the value of the constant UNDEF, there is really no point in keeping the stuff inside the if statement.
Here is how I tested this:
#!/usr/bin/perl -P -MO=Graph,-text use constant UNDEF => 0; my $test = 1; if(UNDEF){ $test = 'Hello World'; } print "\$test => $test\n";

#!/usr/bin/perl -P -MO=Graph,-text my $test = 1; #if 0 $test = 'Hello World'; #endif print "\$test => $test\n";

You can run these 2 programs: ./prog.pl | grep Hello to see if the word "Hello" appears anywhere in the output. Also, if you use a variable instead of a constant, (as in my $UNDEF = 0; ), you'll see that the statement will not be folded and that "Hello" will appear in the output.

Hope this answers your questions.

PS: -MO=Graph,-text will show you an ascii drawing of the tree, while -MO=Graph,-dot will output a dot file that you can view if you have dotty, part of the Graphviz package.

Replies are listed 'Best First'.
Re: Re: Preprocessor Pranks
by ariels (Curate) on May 05, 2002 at 08:38 UTC

    You show that both programs compile to the same thing. However, compilation time is a definite issue for a scripting language. If filtering with <samp>cpp</samp> compiles twice as quickly as using a <samp>constant</samp>, then it is faster for short-lived programs.

    To determine run time of a program, use one of the UN*X <samp>time</samp> commands (either the shell builtin or <samp>/usr/bin/time</samp> or <samp>/usr/bin/timex</samp>). This should give equivalent results to the suggestion given above for using <samp>Benchmark</samp>.

    However, almost surely it does not matter: for very many Perl programs, the compile time is dominated by the run time. Exceptions may include some CGI programs (and hence e.g. <samp>mod_perl</samp>, which seeks to reduce the number of times compilation time is paid).