Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- define("LIMIT",1000000);
- define("SQRT_LIMIT",floor(sqrt(LIMIT)));
- function classic(){
- $sieve = array_fill(2,LIMIT-1,true);
- for($i=2;$i<=SQRT_LIMIT;$i++){
- if($sieve[$i]===true){
- for($j=$i*$i; $j<=LIMIT; $j+=$i){
- $sieve[$j]=false;
- }
- }
- }
- //print_r($sieve);
- }
- function using_string(){
- $sieve = str_repeat("\1", LIMIT+1);
- for($i=2;$i<=SQRT_LIMIT;$i++){
- if($sieve[$i]==="\1"){
- for($j=$i*$i; $j<=LIMIT; $j+=$i){
- $sieve[$j]="\0";
- }
- }
- }
- //$temp=array(); for($i=2;$i<=LIMIT;$i++) if(ord($sieve[$i])) $temp[]=$i; print_r($temp);
- }
- function benchmark($func){
- $memory0 = memory_get_peak_usage();
- $time0 = microtime(TRUE);
- $func();
- $memory1 = memory_get_peak_usage();
- $time1 = microtime(TRUE);
- $delta_mem = $memory1 - $memory0;
- $delta_time = $time1 - $time0;
- $bpe = round($delta_mem / LIMIT, 2);
- $mspe = round(1000*$delta_time, 2);
- echo " $delta_mem b ($bpe b per element), $mspe ms ";
- }
- // Now run
- benchmark("classic");
- // OR (not AND!)
- benchmark("using_string");
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement