Re: multiply by 2
| From: | Bogdan Stancescu | Date: | Mon, 20 May 2002 15:11:38 +0000 |
| Subject: | Re: multiply by 2 | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-98458@lists.php.net to get a copy of this message | ||
Just for confirmation:
Linux Mandrake 8.1, PHP 4.0.6, PIII 600MHz, using Jason's code:
- Original code via HTTP:
1st attempt
3.4497429132462
3.1789749860764
[7.85% faster with bit op's]
2nd attempt (reload)
3.3336659669876
3.1573359966278
[5.29% faster with bit op's]
- Original code from the command line:
[bogdan@localhost bogdan]$ php -q ../httpd/mul.php
3.2482839822769
3.1069300174713
[4.35% faster with bit op's]
[bogdan@localhost bogdan]$ php -q ../httpd/mul.php
3.2525320053101
3.1399850845337
[3.46% faster with bit op's]
- Same code, but with $j*4 and $j<<2:
[bogdan@localhost bogdan]$ php -q ../httpd/mul.php
3.23199903965
[3.0816890001297]
4.65% faster with bit op's
- Same code with $j*256 and $j<<8:
[bogdan@localhost bogdan]$ php -q ../httpd/mul.php
3.2386699914932
3.0807039737701
[4.88% faster with bit op's]
- Original code (*2 and <<1), but also added $q=$p/2; and $q=$p>>1; respectively in the two loops:
[bogdan@localhost bogdan]$ php -q ../httpd/mul.php
4.6924660205841
4.4853490591049
[4.41% faster with bit op's]
Switching the loops (making the bit op's loop first and the multiplication loop second) doesn't change the results.
Bogdan
Jason Wong wrote:
On Monday 20 May 2002 12:03, Martin Towell wrote:I was doing some timing of a function on the weekend and in one of the loops, I had to multiply a variable by 2 - easy enough - $i*2 but then I remembered that in C, it's quicker to do a left shift - so $i<<1 but this actually took longer to execute in php than the $i*2 - can anyone confirm my test? I iterated ~28,000 times. Each time, there was 2 places where I was doing the left shift. The time (including all the other stuff I was doing in the function) for $i*2 was ~12secs, and $i<<1 was ~19secs. I am running PHP4.0.6 (download cgi version from php.net) on a win98 system (500MHz Celeron if that changes anything)My tests don't show much difference, shifting is slightly faster. <?php ini_set('max_execution_time', 600); function gettime() { list($usec, $sec) = explode(" ", microtime()); return ((float)$usec + (float)$sec); } $start=gettime(); $j = 24; for($i = 1; $i <= 1000000; $i++) { $p = $j * 2; #echo $p; } $end=gettime(); echo $end - $start, "\n"; $start=gettime(); $j = 24; for($i = 1; $i <= 1000000; $i++) { $p = $j << 1; #echo $p; } $end=gettime(); echo $end - $start, "\n"; ?> Results ======= [jason@x27 jason]$ php -q doo.php 7.4377170801163 7.2966409921646 [jason@x27 jason]$ php -q doo.php 7.4303779602051 7.2926670312881