php array_assoc detection test

2017-10-16 17:54:46
php assoc_detection.php 50000

Testing array_values
  Total time: 0.96568 s
  Average   : 1.28758 us / test 
  Mempeak   : 530 008 bytes 

Testing array_filter of keys
  Total time: 2.41037 s
  Average   : 3.21382 us / test 
  Mempeak   : 530 008 bytes 

Testing array_keys !== range
  Total time: 1.12681 s
  Average   : 1.50241 us / test 
  Mempeak   : 544 976 bytes 

Testing array_keys comparison
  Total time: 1.38097 s
  Average   : 1.84129 us / test 
  Mempeak   : 544 976 bytes 


array_values is fastest and memory effective array_filter of keys is slowest and still memory effective array_keys against range is quite fast but memory ineffective

php array assoc detection

2017-10-16 17:54:19
<?php

if(!isset($argv[1])){
    echo "Usage: ".$argv[0]." (number of iterations)
";
    exit(1);
}

/**
 * Arrays to check
 */
$tests = array(
    array(array(
        'foo' => 'bar',
    )),
    array(array(
        'bar',
        'foo' => 'bar',
        'baz',
    )),
    array(null),
    array(true),
    array(false),
    array(0),
    array(1),
    array(0.0),
    array(1.0),
    array('string'),
    array(array(0, 1, 2)),
    array(new stdClass),
    array_fill(0,1000,uniqid()),                // big numeric array

    array_fill_keys(range(2,1000,3),uniqid()),  // big misaligned numeric array (=associative)

    array_fill_keys(                            // big associative array
        str_split(
            str_repeat(uniqid('',true),100),
            3
        ),
        true
    )
);

$iterations = (int)$argv[1];

/**
 * Common methods to check associative array
 */
$methods = array(
    'method1 (array_values check)' => function($array){
        return array_values($array) !== $array;
    },
    'method2 (array_keys comparison)' => function($array){
        $array = array_keys($array); return ($array !== array_keys($array));
    },
    'method3 (array_filter of keys)' => function($array){
        return count(array_filter(array_keys($array), 'is_string')) > 0;
    },
    'array_keys !== range' => function($array) {
        return array_keys($array) !== range(0, count($array) - 1);
    },
);

$keys = array_keys($methods);
shuffle($keys);
$methods_new = [];
foreach ($keys as $key) {
    $methods_new[$key] = $methods[$key];
}
$methods = $methods_new;
unset($methods_new);


if (!extension_loaded('pcntl') && !dl('pcntl.so')) die("no pcntl.so
");

foreach($methods as $name=>$func){
    switch (pcntl_fork()) {
    case -1: die("couldnot fork
");
    case 0:
    echo "Testing $name - $iterations iterations
";
    $time = microtime(true);

    for($x=0;$x<$iterations;$x++){
        foreach($tests as $array){
            $func($array);
        }
    }

    /**
     * Show results
     */
    $totalTime = (microtime(true) - $time);
    $avgTime = $totalTime / ($iterations * count($tests));

    echo "  Total time: ".number_format($totalTime,5,'.',' ')." s
";
    echo "  Average   : ".number_format($avgTime*1e6,5,'.',' ')." us / test 
";
    echo "  Mempeak   : ".number_format(memory_get_peak_usage(),0,'.',' ')." bytes 
";
    echo "
";
    exit(0);
    break;
    default: pcntl_wait($status);
    }
}



Installing php on macos

2017-10-16 16:22:44
brew install openssl

cd ~/Downloads

curl -O http://php.net/get/php-7.1.10.tar.bz2/from/a/mirror

tar xf php...

./configure  --disable-all --enable-fpm --enable-libxml --with-openssl=/Users/ezh/homebrew/opt/openssl --with-zlib --with-sqlite3 --enable-mysqlnd --prefix=/local/php --exec-prefix=/local/php

make -j4

make install

brew install autoconf

/local/php/bin/phpize ; and ./configure --prefix=/local/php --with-php-config=/local/php/bin/php-config ; and make install

Разминка

2017-05-01 11:06:08
Повороты головы из стороны в сторону, кивание вверх-вниз, вращательные движения головой. Вращательные движения кистями рук по часовой и против часовой стрелки. Вращательные движения в локтевых суставах. Разминка плечевых суставов. Подъемы рук через стороны вверх, «ножницы» руками перед грудью, вращательные движения. Наклоны корпуса вперед и в стороны. Вращение тазом попеременно в обе стороны. Махи ногами вперед-назад и в сторону. Сгибания-разгибания в коленном суставе. Сидя с вытянутыми ногами, вращение в голеностопе попеременно в обе стороны.

Add arbitrary numbers

2017-02-13 18:18:23

function add($a, $b) {
    $r = '';
    $a = str_split(strrev($a));
    $b = str_split(strrev($b));
    if (count($b) > count($a)) {
        $tmp = $a;
        $a = $b;
        $b = $tmp;
    }
    for ($carry = 0, $idx = 0; isset($a[$idx]) || $carry; $idx++) {
        $value = (int)($a[$idx] ?? 0) + (int)($b[$idx] ?? 0) + $carry;
        if ($carry = (int)($value > 9)) $value -= 10;
        $r .= $value;
    }
    return strrev($r);
}

204

2017-01-12 15:44:40
$window = function ($window_size) {
    $window = [];
    $window_ptr = 0;
    $avg = 0;
    while (true) {
        $value = (yield $avg);
        if ($value === null) break;
        $window[$window_ptr] = $value;
        $window_ptr = ($window_ptr + 1) % $window_size;
        $avg = array_sum($window) / count($window);
    }
};

/** @var Generator $windowed_avg */
$windowed_avg = $window(10);
foreach ([10, 20, 30, 40, 50, 60, 70, 80, 90, 10, 10, 10, 10] as $v) {
    $avg = $windowed_avg->send($v);
    echo "sent $v got $avg\n";
}

203

2017-01-12 15:44:27
class defer {
        private $cb;
        public function __construct($cb) {$this->cb = $cb;}
        public function __destruct() {$cb = $this->cb; $cb();}
}

$log_id = \Logs::addLog(CLASS_DB, new \LogScreen());
$defer = new \defer(function() use ($log_id) { \Logs::delLog(CLASS_DB, $log_id);});

function cpusleep($cpu_time) {
    $cur = $prev_cur = $start = microtime(true);
    $cycle_time = 1e-5;
    $cycles = 1;
    $cycle_time_reaction = 1;

    while (($left = $cpu_time - ($cur - $start)) > 0) {
        $cycle_time = ($cycle_time + ($cur - $prev_cur) / $cycles) * $cycle_time_reaction / (1 + $cycle_time_reaction);
        $cycles = $left / $cycle_time;
        for ($i = 0; $i < $cycles; $i++);
        $prev_cur = $cur;
        $cur = microtime(true);
    }
}

function ru($msg, $ru_param = null) {
    $ru = $ru_param !== null ? getrusage($ru_param) : getrusage();
    echo "$msg:" . ($ru['ru_utime.tv_sec'] * 1e6 + $ru['ru_utime.tv_usec']) . "\n";
}

function sleep_period($epoch_period) {
        $now_ms = microtime(true) * 1000;
        $epoch_ms = (((int)($now_ms / $epoch_period)) + 1) * $epoch_period;
        usleep(($epoch_ms - $now_ms) * 1000);
}

202

2017-01-12 15:44:07
function utf8_encode2($num) {
    if ($num <= 0x7f) {
        return chr($num);
    } else if ($num <= 0x07ff) {
        return chr(0xc0 | ($num >> 6)) . chr(0x80 | ($num & 0x3f));
    } else if ($num <= 0xffff) {
        return chr(0xe0 | ($num >> 12)) . chr(0x80 | ($num >> 10 & 0x3f)) . chr(0x80 | ($num & 0x3f));
    } else if ($num <= 0x1fffff) {
        return chr(0xf0 | ($num >> 18)) . chr(0x80 | ($num >> 12 & 0x2f)) . chr(0x80 | ($num >> 6 & 0x3f)) . chr($num & 0x3f);
    }
}

201

2017-01-12 15:43:41
/**
 * Makes ANSI escape seq for 256 color, each color comp is 0..5
 */
function tc2e($r, $g, $b) {
    return "\33[38;5;" . ($r * 36 + $g * 6 + $b + 16) . "m";
}

function c($s, $k) {
    $res = ["\r\33[2K"];
    foreach (str_split($s, floor(strlen($s) / 12) + 1) as $j => $chunk) {
        $res[] = tc2e(
            0,
            1 + abs(4 - (($k + $j) % 9)),
            0) . $chunk;
    }
    return implode('', $res);
}

if (!stream_set_blocking(STDIN, 0)) die("could not set stream to nonblocking\n");

proc_close(proc_open('stty -icanon -echo -echoe', array(STDIN, STDOUT, STDERR), $pp));

$i = 0;
$s = '';
while (true) {
    $c = fgets(STDIN);
    if (feof(STDIN)) break;
    if ($c !== false) {
        foreach (str_split($c) as $c) {
            if ($c === "\4" || $c == "\33") {
                break 2;
            } else if ($c == "\x7f") { /*backspace*/
                $s = substr($s, 0, -1);
            } else if ($c == "\n") {
                echo "\r\33[2K\33[0m$s\n";
                $s = '';
            } else {
                $s .= $c;
            }
        }
    }
    $i++;
    echo c($s, $i);
    usleep(100000);
}
proc_close(proc_open('stty sane', array(STDIN, STDOUT, STDERR), $pp));

200

2017-01-12 15:02:51
class LogEm {
    const TILL_RETURN = 1;
    const TILL_COMMIT_ROLLBACK = 2;
    private $cb;
    static $log_id = null;
    function __construct($cb) {
        $this->cb = $cb;
    }
    function __destruct() {
        call_user_func_array($this->cb, [self::$log_id]);
        self::$log_id = null;
    }
    static function delLog() {
        Logs::delLog(CLASS_DB, self::$log_id);
    }
    static function sql($till, $file, $line, $msg = '') {
        file_put_contents('/tmp/emakhrov.log', sprintf("%s:%s %s\n", $file, $line, $msg), FILE_APPEND);
        if (self::$log_id !== null) return null;
        self::$log_id = \Logs::addLog(CLASS_DB, new LogFile('/tmp/sql_emakhrov.log'));
        if ($till == self::TILL_RETURN) return new self(array(__CLASS__, 'delLog'));
        ConnectionManager::addCommitCallBack(array(__CLASS__, 'delLog'), []);
        ConnectionManager::addRollbackCallBack(array(__CLASS__, 'delLog'), []);
    }
}


examples:
$ololo = LogEm::SQL(LogEm::TILL_RETURN, __METHOD__, __LINE__, $this->real_command);

LogEm::sql(LogEm::TILL_COMMIT_ROLLBACK, __FILE__, __LINE__);

21 20 19 18 1