Alex Rivera | Logout

integer division in php

Asked 2010-04-20T08:58:11.470
24

I'm looking for the fastest way to do an integer division in php. for example, 5 / 2 should be 2 and 6 / 2 should be 3 and so on. If I simply do this, php will return 2.5 in the first case, the only solution I could find was using intval($my_number/2) - which isn't as fast as I want it to be (but gives the expected results).

How can I do this?

EDIT:
Thanks to all of you for your ideas, I used the script posted by rubber_boots to test some of them with 10000000 iterations, here you can see the results (MAMP on a 3 or 4 year old MacBook with 2Ghz Intel core 2 duo):

start (10000000)
(int)...: 2.26 sec
floor(): 4.36 sec
int_divide(): 2.86 sec
bit-shift: 1.45 sec //note: only works for divisions through powers of 2
intval(): 4.51 sec
round() with PHP_ROUND_HALF_DOWN: 5.48 sec

until now, bit-shift is the fastest way, but I'll leave this question open for a day to see if there are other possibilities for this...

EDIT2:
updated the results, added round() with PHP_ROUND_HALF_DOWN (thanks to Col._Shrapnel)

Edit
Report

1 Answer

4

Just Test it:

Result (Win32, Core2/E6600):

 generic division (3000000)
 (int)DIV:       1.74 sec
 intval(DIV):    6.90 sec
 floor(DIV):     6.92 sec
 int_divide():   1.85 sec

 division by 2 (3000000)
 (int)(VAL/2):   1.75 sec
 VAL >> 2:       1.63 sec
 (int)(VAL*0.5): 1.72 sec

Code:

 ...
 echo "generic division ($N)\n";
 $start = getTime(); for($i=1; $i<$N; $i++) { $c = (int)(($i+1) / $i); }
 printf("(int)DIV:\t %.2f sec\n", getTime()-$start);

 $start = getTime(); for($i=1; $i<$N; $i++) { $c = intval(($i+1) / $i); }
 printf("intval(DIV):\t %.2f sec\n", getTime()-$start);

 $start = getTime(); for($i=1; $i<$N; $i++) { $c = floor(($i+1) / $i); }
 printf("floor(DIV):\t %.2f sec\n", getTime()-$start);

 $start = getTime(); for($i=1; $i<$N; $i++) { $c = ($i - ($i % ($i+1))) / ($i+1); }
 printf("int_divide():\t %.2f sec\n", getTime()-$start);

 echo "division by 2 ($N)\n";
 $start = getTime(); for($i=1; $i<$N; $i++) { $c = (int)(($i+1) / 2.0); }
 printf("(int)(VAL/2):\t %.2f sec\n", getTime()-$start);

 $start = getTime(); for($i=1; $i<$N; $i++) { $c = ($i+1) >> 2; }
 printf("VAL >> 2:\t %.2f sec\n", getTime()-$start);

 $start = getTime(); for($i=1; $i<$N; $i++) { $c = (int)(($i+1)*0.5); }
 printf("(int)(VAL*0.5):\t %.2f sec\n", getTime()-$start);
 ...

Regards

rbo

answered 2010-04-20T09:31:35.490

Your Answer