Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Mar 20th, 2010  |  syntax: PHP  |  size: 1.04 KB  |  views: 169  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
This paste has a previous version, view the difference. Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. <?php
  2. function array_key_exists_test( $n )
  3. {
  4.     //setup the array
  5.     $array = array();
  6.     $set_key_count = (int)($n/2);
  7.     for( $i = 0; $i < $set_key_count; $i++ ) {
  8.         do {
  9.             $rand_number = rand( 0, $n-1 );
  10.         } while( array_key_exists( $rand_number, $array ) );
  11.         $array[$rand_number] = NULL;
  12.     }
  13.     $test_array = range( 0, $n-1 );
  14.     shuffle( $test_array );
  15.     $result_array = array();
  16.    
  17.     $start = microtime(true);
  18.    
  19.     foreach( $test_array as $test_number ) {
  20.         if( array_key_exists( $test_number, $array ) ) {
  21.             $result_array[] = $test_number;
  22.         }
  23.     }
  24.    
  25.     $stop = microtime(true);
  26.    
  27.     if( count( $result_array ) !== $set_key_count )
  28.         throw new Exception( "test failed" );
  29.    
  30.     return ( $stop - $start ) / $n;
  31. }
  32.  
  33. $n_array = range( 1, 100 );
  34. $n_array = array_map( function( $n ) { return $n * 10000; }, $n_array );
  35. foreach( $n_array as $n ) {
  36.     print sprintf( "at n of %d time per call %.10f\n", $n, array_key_exists_test( $n ) );
  37. }
  38.  
  39. ?>
clone this paste RAW Paste Data