in reply to Re: Simple Rounding
in thread Simple Rounding

My first thought was, 'Silly guy, why is he writing C code? Doesn't he know the Perl(tm) way?'.

Then I thought, sprintf() is expensive .... how fast is it to run the integer math?

use strict; use warnings; use diagnostics; use Benchmark qw( :all );; my ( $number, $num ); $number = 1100.64686081907; cmpthese( -1, { sprintf => sub { $num = sprintf "%.2f", $number; }, round => sub { $num = int( $number * 100 + .5 ) / 10 +0; }, } ); # produced the results ... Rate sprintf round sprintf 123242/s -- -86% round 851644/s 591% --

So integer math rounding is 6 times as fast as using sprintf.

Of course, if you're doing less than 50,000, you may not notice the time difference, especially if you blink.

--
TTTATCGGTCGTTATATAGATGTTTGCA

Replies are listed 'Best First'.
Re: Blushing at the facts
by Abigail-II (Bishop) on Mar 25, 2004 at 16:47 UTC
    There is a subtle, but important difference between
    $var1 = sprintf "%.2f" => $number;
    and
    $var2 = int ($number * 100 + .5) / 100;
    $var1 is a PV, that is, the interval variable has a string value, but not a numeric value, while $var2 is an NV, that is, it has a numeric value, but not a string value. This means that $var1 will have two digits after the decimal point when printed - sprintf has garanteed that. But that's not necessarely true for $var2. Since you cannot represent 1/100 exactly in binary, you left the possibility open that if you stringify the number, you end up with more than 2 characters after the decimal point. Now, it may not happen in a thousand testcases, but can you guarantee it will never happen?

    See perldoc -q decimal.