Example #1
0
/**
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
 * in moodlelib.php. This function is here so that we can 
 * call it before all the libs are pulled in. 
 *
 * @uses $PERF
 */
function init_performance_info()
{
    global $PERF, $CFG, $USER;
    $PERF = new Object();
    $PERF->dbqueries = 0;
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
    }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();
    }
    if (function_exists('apd_set_pprof_trace')) {
        // APD profiling
        if ($USER->id > 0 && $CFG->perfdebug >= 15) {
            $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
            mkdir($tempdir);
            apd_set_pprof_trace($tempdir);
            $PERF->profiling = true;
        }
    }
}
Example #2
0
 public function __construct()
 {
     $state = '';
     if (function_exists('posix_times')) {
         $state .= serialize(posix_times());
     }
     $state .= getmypid() . memory_get_usage();
     $state .= serialize($_ENV);
     $this->state = hash('sha512', $state, true);
 }
Example #3
0
/**
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
 * in moodlelib.php. This function is here so that we can 
 * call it before all the libs are pulled in. 
 *
 * @uses $PERF
 */
function init_performance_info()
{
    global $PERF;
    $PERF = new Object();
    $PERF->dbqueries = 0;
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
    }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();
    }
}
Example #4
0
 public function stop()
 {
     $this->endreadable = date(DATE_ATOM);
     $this->endtime = microtime(true);
     $this->endptimes = posix_times();
     $this->serverloadend = $this->get_load();
     $this->realtime = $this->endtime - $this->starttime;
     $this->endmemorytotal = memory_get_usage();
     $this->endmemorytotalreal = memory_get_usage(true);
     $this->memorypeak = memory_get_peak_usage();
     $this->memorypeakreal = memory_get_peak_usage(true);
     $this->stopptimes = posix_times();
     $info = array();
     foreach ($this->stopptimes as $key => $val) {
         $info[$key] = $this->stopptimes[$key] - $this->startptimes[$key];
     }
     $this->ticks = "Ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
 }
Example #5
0
 public function __construct()
 {
     $state = self::$state;
     if (function_exists('posix_times')) {
         $state .= serialize(posix_times());
     }
     if (function_exists('zend_thread_id')) {
         $state .= zend_thread_id();
     }
     $state .= getmypid() . memory_get_usage();
     $state .= serialize($_ENV);
     $state .= serialize($_SERVER);
     $state .= count(debug_backtrace(false));
     self::$state = hash('sha512', $state, true);
     if (is_null(self::$counter)) {
         list(, self::$counter) = unpack("i", substr(self::$state, 0, 4));
         $seed = $this->generate(strlen(dechex(PHP_INT_MAX)));
         list(, self::$counter) = unpack("i", $seed);
     }
 }
Example #6
0
/**
 * get_performance_info() pairs up with init_performance_info()
 * loaded in setup.php. Returns an array with 'html' and 'txt'
 * values ready for use, and each of the individual stats provided
 * separately as well.
 *
 * @global object
 * @global object
 * @global object
 * @return array
 */
function get_performance_info()
{
    global $CFG, $PERF, $DB, $PAGE;
    $info = array();
    $info['html'] = '';
    // holds userfriendly HTML representation
    $info['txt'] = me() . ' ';
    // holds log-friendly representation
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
    $info['html'] .= '<span class="timeused">' . $info['realtime'] . ' secs</span> ';
    $info['txt'] .= 'time: ' . $info['realtime'] . 's ';
    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<span class="memoryused">RAM: ' . display_size($info['memory_total']) . '</span> ';
        $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') ';
    }
    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<span class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</span> ';
        $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') ';
    }
    $inc = get_included_files();
    //error_log(print_r($inc,1));
    $info['includecount'] = count($inc);
    $info['html'] .= '<span class="included">Included ' . $info['includecount'] . ' files</span> ';
    $info['txt'] .= 'includecount: ' . $info['includecount'] . ' ';
    $filtermanager = filter_manager::instance();
    if (method_exists($filtermanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    $stringmanager = get_string_manager();
    if (method_exists($stringmanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    $jsmodules = $PAGE->requires->get_loaded_modules();
    if ($jsmodules) {
        $yuicount = 0;
        $othercount = 0;
        $details = '';
        foreach ($jsmodules as $module => $backtraces) {
            if (strpos($module, 'yui') === 0) {
                $yuicount += 1;
            } else {
                $othercount += 1;
            }
            $details .= "<div class='yui-module'><p>{$module}</p>";
            foreach ($backtraces as $backtrace) {
                $details .= "<div class='backtrace'>{$backtrace}</div>";
            }
            $details .= '</div>';
        }
        $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: {$yuicount}</span> ";
        $info['txt'] .= "includedyuimodules: {$yuicount} ";
        $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: {$othercount}</span> ";
        $info['txt'] .= "includedjsmodules: {$othercount} ";
        // Slightly odd to output the details in a display: none div. The point
        // Is that it takes a lot of space, and if you care you can reveal it
        // using firebug.
        $info['html'] .= '<div id="yui-module-debug" class="notifytiny">' . $details . '</div>';
    }
    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<span class="logwrites">Log DB writes ' . $info['logwrites'] . '</span> ';
        $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' ';
    }
    $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites);
    $info['html'] .= '<span class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</span> ';
    $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' ';
    if (!empty($PERF->profiling) && $PERF->profiling) {
        require_once $CFG->dirroot . '/lib/profilerlib.php';
        $info['html'] .= '<span class="profilinginfo">' . Profiler::get_profiling(array('-R')) . '</span>';
    }
    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> ";
            $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
        }
    }
    // Grab the load average for the last minute
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices
    if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
        list($server_load) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else {
        if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
            if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
                $server_load = $matches[1];
            } else {
                trigger_error('Could not parse uptime output!');
            }
        }
    }
    if (!empty($server_load)) {
        $info['serverload'] = $server_load;
        $info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }
    // Display size of session if session started
    if (session_id()) {
        $info['sessionsize'] = display_size(strlen(session_encode()));
        $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> ';
        $info['txt'] .= "Session: {$info['sessionsize']} ";
    }
    /*    if (isset($rcache->hits) && isset($rcache->misses)) {
            $info['rcachehits'] = $rcache->hits;
            $info['rcachemisses'] = $rcache->misses;
            $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
                "{$rcache->hits}/{$rcache->misses}</span> ";
            $info['txt'] .= 'rcache: '.
                "{$rcache->hits}/{$rcache->misses} ";
        }*/
    $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>';
    return $info;
}
Example #7
0
/**
 *** get_performance_info() pairs up with init_performance_info()
 *** loaded in setup.php. Returns an array with 'html' and 'txt'
 *** values ready for use, and each of the individual stats provided
 *** separately as well.
 ***
 **/
function get_performance_info()
{
    global $CFG, $PERF, $rcache;
    $info = array();
    $info['html'] = '';
    // holds userfriendly HTML representation
    $info['txt'] = me() . ' ';
    // holds log-friendly representation
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
    $info['html'] .= '<span class="timeused">' . $info['realtime'] . ' secs</span> ';
    $info['txt'] .= 'time: ' . $info['realtime'] . 's ';
    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<span class="memoryused">RAM: ' . display_size($info['memory_total']) . '</span> ';
        $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') ';
    }
    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<span class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</span> ';
        $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') ';
    }
    $inc = get_included_files();
    //error_log(print_r($inc,1));
    $info['includecount'] = count($inc);
    $info['html'] .= '<span class="included">Included ' . $info['includecount'] . ' files</span> ';
    $info['txt'] .= 'includecount: ' . $info['includecount'] . ' ';
    if (!empty($PERF->dbqueries)) {
        $info['dbqueries'] = $PERF->dbqueries;
        $info['html'] .= '<span class="dbqueries">DB queries ' . $info['dbqueries'] . '</span> ';
        $info['txt'] .= 'dbqueries: ' . $info['dbqueries'] . ' ';
    }
    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<span class="logwrites">Log writes ' . $info['logwrites'] . '</span> ';
        $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' ';
    }
    if (!empty($PERF->profiling) && $PERF->profiling) {
        require_once $CFG->dirroot . '/lib/profilerlib.php';
        $info['html'] .= '<span class="profilinginfo">' . Profiler::get_profiling(array('-R')) . '</span>';
    }
    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> ";
            $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
        }
    }
    // Grab the load average for the last minute
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices
    if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
        list($server_load) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else {
        if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
            if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
                $server_load = $matches[1];
            } else {
                trigger_error('Could not parse uptime output!');
            }
        }
    }
    if (!empty($server_load)) {
        $info['serverload'] = $server_load;
        $info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }
    if (isset($rcache->hits) && isset($rcache->misses)) {
        $info['rcachehits'] = $rcache->hits;
        $info['rcachemisses'] = $rcache->misses;
        $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : ' . "{$rcache->hits}/{$rcache->misses}</span> ";
        $info['txt'] .= 'rcache: ' . "{$rcache->hits}/{$rcache->misses} ";
    }
    $info['html'] = '<div class="performanceinfo">' . $info['html'] . '</div>';
    return $info;
}
Example #8
0
 protected static function random_pseudo_bytes($length)
 {
     if (self::openssl_random_pseudo_bytes_exists()) {
         return openssl_random_pseudo_bytes($length);
     }
     if (self::mcrypt_dev_urandom_exists()) {
         $rnd = mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
         if ($rnd !== false) {
             return $rnd;
         }
     }
     // Rename the parameter on order it to fit with the code below.
     $len = $length;
     /*
      * The following code fragment has been taken from Secure-random-bytes-in-PHP
      * project, released under the New BSD License.
      * @see https://github.com/ivantcholakov/Secure-random-bytes-in-PHP
      *
      *
      *
      * Author:
      * George Argyros <*****@*****.**>
      *
      * Copyright (c) 2012, George Argyros
      * All rights reserved.
      *
      * Redistribution and use in source and binary forms, with or without
      * modification, are permitted provided that the following conditions are met:
      *    * Redistributions of source code must retain the above copyright
      *      notice, this list of conditions and the following disclaimer.
      *    * Redistributions in binary form must reproduce the above copyright
      *      notice, this list of conditions and the following disclaimer in the
      *      documentation and/or other materials provided with the distribution.
      *    * Neither the name of the <organization> nor the
      *      names of its contributors may be used to endorse or promote products
      *      derived from this software without specific prior written permission.
      *
      * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
      * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
      * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
      * DISCLAIMED. IN NO EVENT SHALL GEORGE ARGYROS BE LIABLE FOR ANY
      * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
      * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
      * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
      * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
      * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
      * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
      *
      *
      *
      * The function is providing, at least at the systems tested :),
      * $len bytes of entropy under any PHP installation or operating system.
      * The execution time should be at most 10-20 ms in any system.
      */
     $SSLstr = '4';
     // http://xkcd.com/221/
     /*
      * No build-in crypto randomness function found. We collect any entropy
      * available in the PHP core PRNGs along with some filesystem info and memory
      * stats. To make this data cryptographically strong we add data either from
      * /dev/urandom or if its unavailable, we gather entropy by measuring the
      * time needed to compute a number of SHA-1 hashes.
      */
     $str = '';
     $bits_per_round = 2;
     // bits of entropy collected in each clock drift round
     $msec_per_round = 400;
     // expected running time of each round in microseconds
     $hash_len = 20;
     // SHA-1 Hash length
     $total = $len;
     // total bytes of entropy to collect
     $handle = @fopen('/dev/urandom', 'rb');
     if ($handle && function_exists('stream_set_read_buffer')) {
         @stream_set_read_buffer($handle, 0);
     }
     do {
         $bytes = $total > $hash_len ? $hash_len : $total;
         $total -= $bytes;
         //collect any entropy available from the PHP system and filesystem
         $entropy = rand() . uniqid(mt_rand(), true) . $SSLstr;
         $entropy .= implode('', @fstat(@fopen(__FILE__, 'r')));
         $entropy .= memory_get_usage() . getmypid();
         $entropy .= serialize($_ENV) . serialize($_SERVER);
         if (function_exists('posix_times')) {
             $entropy .= serialize(posix_times());
         }
         if (function_exists('zend_thread_id')) {
             $entropy .= zend_thread_id();
         }
         if ($handle) {
             $entropy .= @fread($handle, $bytes);
         } else {
             // Measure the time that the operations will take on average
             for ($i = 0; $i < 3; $i++) {
                 $c1 = microtime(true);
                 $var = sha1(mt_rand());
                 for ($j = 0; $j < 50; $j++) {
                     $var = sha1($var);
                 }
                 $c2 = microtime(true);
                 $entropy .= $c1 . $c2;
             }
             // Based on the above measurement determine the total rounds
             // in order to bound the total running time.
             $rounds = (int) ($msec_per_round * 50 / (int) (($c2 - $c1) * 1000000));
             // Take the additional measurements. On average we can expect
             // at least $bits_per_round bits of entropy from each measurement.
             $iter = $bytes * (int) ceil(8 / $bits_per_round);
             for ($i = 0; $i < $iter; $i++) {
                 $c1 = microtime();
                 $var = sha1(mt_rand());
                 for ($j = 0; $j < $rounds; $j++) {
                     $var = sha1($var);
                 }
                 $c2 = microtime();
                 $entropy .= $c1 . $c2;
             }
         }
         // We assume sha1 is a deterministic extractor for the $entropy variable.
         $str .= sha1($entropy, true);
         // Modified by Deepak Patil <*****@*****.**>, 16-MAR-2015.
         //} while ($len > strlen($str));
     } while ($len > self::strlen($str));
     //
     if ($handle) {
         @fclose($handle);
     }
     // Modified by Deepak Patil <*****@*****.**>, 16-MAR-2015.
     //return substr($str, 0, $len);
     return self::substr($str, 0, $len);
     //
     /*
      * End of code fragment from Secure-random-bytes-in-PHP project.
      */
 }
/**
 * get_performance_info() pairs up with init_performance_info()
 * loaded in setup.php. Returns an array with 'html' and 'txt'
 * values ready for use, and each of the individual stats provided
 * separately as well.
 *
 * @return array
 */
function get_performance_info()
{
    global $CFG, $PERF, $DB, $PAGE;
    $info = array();
    $info['html'] = '';
    // Holds userfriendly HTML representation.
    $info['txt'] = me() . ' ';
    // Holds log-friendly representation.
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
    $info['html'] .= '<span class="timeused">' . $info['realtime'] . ' secs</span> ';
    $info['txt'] .= 'time: ' . $info['realtime'] . 's ';
    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<span class="memoryused">RAM: ' . display_size($info['memory_total']) . '</span> ';
        $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') ';
    }
    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<span class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</span> ';
        $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') ';
    }
    $inc = get_included_files();
    $info['includecount'] = count($inc);
    $info['html'] .= '<span class="included">Included ' . $info['includecount'] . ' files</span> ';
    $info['txt'] .= 'includecount: ' . $info['includecount'] . ' ';
    if (!empty($CFG->early_install_lang) or empty($PAGE)) {
        // We can not track more performance before installation or before PAGE init, sorry.
        return $info;
    }
    $filtermanager = filter_manager::instance();
    if (method_exists($filtermanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    $stringmanager = get_string_manager();
    if (method_exists($stringmanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='{$key}'>{$nicenames[$key]}: {$value} </span> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    $jsmodules = $PAGE->requires->get_loaded_modules();
    if ($jsmodules) {
        $yuicount = 0;
        $othercount = 0;
        $details = '';
        foreach ($jsmodules as $module => $backtraces) {
            if (strpos($module, 'yui') === 0) {
                $yuicount += 1;
            } else {
                $othercount += 1;
            }
            if (!empty($CFG->yuimoduledebug)) {
                // Hidden feature for developers working on YUI module infrastructure.
                $details .= "<div class='yui-module'><p>{$module}</p>";
                foreach ($backtraces as $backtrace) {
                    $details .= "<div class='backtrace'>{$backtrace}</div>";
                }
                $details .= '</div>';
            }
        }
        $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: {$yuicount}</span> ";
        $info['txt'] .= "includedyuimodules: {$yuicount} ";
        $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: {$othercount}</span> ";
        $info['txt'] .= "includedjsmodules: {$othercount} ";
        if ($details) {
            $info['html'] .= '<div id="yui-module-debug" class="notifytiny">' . $details . '</div>';
        }
    }
    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<span class="logwrites">Log DB writes ' . $info['logwrites'] . '</span> ';
        $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' ';
    }
    $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites);
    $info['html'] .= '<span class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</span> ';
    $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' ';
    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<span class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</span> ";
            $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
        }
    }
    // Grab the load average for the last minute.
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices.
    if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
        list($serverload) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else {
        if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
            if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
                $serverload = $matches[1];
            } else {
                trigger_error('Could not parse uptime output!');
            }
        }
    }
    if (!empty($serverload)) {
        $info['serverload'] = $serverload;
        $info['html'] .= '<span class="serverload">Load average: ' . $info['serverload'] . '</span> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }
    // Display size of session if session started.
    if ($si = \core\session\manager::get_performance_info()) {
        $info['sessionsize'] = $si['size'];
        $info['html'] .= $si['html'];
        $info['txt'] .= $si['txt'];
    }
    if ($stats = cache_helper::get_stats()) {
        $html = '<span class="cachesused">';
        $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
        $text = 'Caches used (hits/misses/sets): ';
        $hits = 0;
        $misses = 0;
        $sets = 0;
        foreach ($stats as $definition => $stores) {
            $html .= '<span class="cache-definition-stats">';
            $html .= '<span class="cache-definition-stats-heading">' . $definition . '</span>';
            $text .= "{$definition} {";
            foreach ($stores as $store => $data) {
                $hits += $data['hits'];
                $misses += $data['misses'];
                $sets += $data['sets'];
                if ($data['hits'] == 0 and $data['misses'] > 0) {
                    $cachestoreclass = 'nohits';
                } else {
                    if ($data['hits'] < $data['misses']) {
                        $cachestoreclass = 'lowhits';
                    } else {
                        $cachestoreclass = 'hihits';
                    }
                }
                $text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) ";
                $html .= "<span class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</span>";
            }
            $html .= '</span>';
            $text .= '} ';
        }
        $html .= "<span class='cache-total-stats'>Total: {$hits} / {$misses} / {$sets}</span>";
        $html .= '</span> ';
        $info['cachesused'] = "{$hits} / {$misses} / {$sets}";
        $info['html'] .= $html;
        $info['txt'] .= $text . '. ';
    } else {
        $info['cachesused'] = '0 / 0 / 0';
        $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
        $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
    }
    $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>';
    return $info;
}
Example #10
0
/**
 * get_performance_info() pairs up with init_performance_info()
 * loaded in setup.php. Returns an array with 'html' and 'txt'
 * values ready for use, and each of the individual stats provided
 * separately as well.
 *
 * @global object
 * @global object
 * @global object
 * @return array
 */
function get_performance_info() {
    global $CFG, $PERF, $DB, $PAGE;

    $info = array();
    $info['html'] = '';         // holds userfriendly HTML representation
    $info['txt']  = me() . ' '; // holds log-friendly representation

    $info['realtime'] = microtime_diff($PERF->starttime, microtime());

    $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
    $info['txt'] .= 'time: '.$info['realtime'].'s ';

    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
        $info['txt']  .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
    }

    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
        $info['txt']  .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
    }

    $inc = get_included_files();
    //error_log(print_r($inc,1));
    $info['includecount'] = count($inc);
    $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
    $info['txt']  .= 'includecount: '.$info['includecount'].' ';

    $filtermanager = filter_manager::instance();
    if (method_exists($filtermanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
            $info['txt'] .= "$key: $value ";
        }
    }

    $stringmanager = get_string_manager();
    if (method_exists($stringmanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
            $info['txt'] .= "$key: $value ";
        }
    }

     $jsmodules = $PAGE->requires->get_loaded_modules();
     if ($jsmodules) {
         $yuicount = 0;
         $othercount = 0;
         $details = '';
         foreach ($jsmodules as $module => $backtraces) {
             if (strpos($module, 'yui') === 0) {
                 $yuicount += 1;
             } else {
                 $othercount += 1;
             }
             if (!empty($CFG->yuimoduledebug)) {
                 // hidden feature for developers working on YUI module infrastructure
                 $details .= "<div class='yui-module'><p>$module</p>";
                 foreach ($backtraces as $backtrace) {
                     $details .= "<div class='backtrace'>$backtrace</div>";
                 }
                 $details .= '</div>';
             }
         }
         $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
         $info['txt'] .= "includedyuimodules: $yuicount ";
         $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
         $info['txt'] .= "includedjsmodules: $othercount ";
         if ($details) {
             $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
         }
     }

    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
        $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
    }

    $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
    $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
    $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';

    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] -  $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
            $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
        }
    }

    // Grab the load average for the last minute
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices
    if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
        list($server_load) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
        if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
            $server_load = $matches[1];
        } else {
            trigger_error('Could not parse uptime output!');
        }
    }
    if (!empty($server_load)) {
        $info['serverload'] = $server_load;
        $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }

    // Display size of session if session started
    if (session_id()) {
        $info['sessionsize'] = display_size(strlen(session_encode()));
        $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> ';
        $info['txt'] .= "Session: {$info['sessionsize']} ";
    }

/*    if (isset($rcache->hits) && isset($rcache->misses)) {
        $info['rcachehits'] = $rcache->hits;
        $info['rcachemisses'] = $rcache->misses;
        $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
            "{$rcache->hits}/{$rcache->misses}</span> ";
        $info['txt'] .= 'rcache: '.
            "{$rcache->hits}/{$rcache->misses} ";
    }*/

    if ($stats = cache_helper::get_stats()) {
        $html = '<span class="cachesused">';
        $html .= '<span class="cache-stats-heading">Caches interaction by definition then store</span>';
        $text = 'Caches used (hits/misses/sets): ';
        $hits = 0;
        $misses = 0;
        $sets = 0;
        foreach ($stats as $definition => $stores) {
            $html .= '<span class="cache-definition-stats">'.$definition.'</span>';
            $text .= "$definition {";
            foreach ($stores as $store => $data) {
                $hits += $data['hits'];
                $misses += $data['misses'];
                $sets += $data['sets'];
                $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
                $html .= "<span class='cache-store-stats'>$store: $data[hits] / $data[misses] / $data[sets]</span>";
            }
            $text .= '} ';
        }
        $html .= "<span class='cache-total-stats'>Total Hits / Misses / Sets : $hits / $misses / $sets</span>";
        $html .= '</span> ';
        $info['cachesused'] = "$hits / $misses / $sets";
        $info['html'] .= $html;
        $info['txt'] .= $text.'. ';
    } else {
        $info['cachesused'] = '0 / 0 / 0';
        $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
        $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
    }

    $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
    return $info;
}
Example #11
0
 function getStats()
 {
     if (!isset($this->_times)) {
         // posix_times() not available.
         return sprintf("real: %.3f", $this->getTime('real'));
     }
     $now = posix_times();
     return sprintf("real: %.3f, user: %.3f, sys: %.3f", $this->getTime('real'), $this->getTime('utime', $now), $this->getTime('stime', $now));
 }
Example #12
0
VERIFY(posix_getpgrp());
VERIFY(posix_getpid());
VERIFY(posix_getppid());
$ret = posix_getpwnam("root");
VERIFY($ret != false);
VERIFY(count((array) $ret) != 0);
VS(posix_getpwnam(""), false);
VS(posix_getpwnam(-1), false);
$ret = posix_getpwuid(0);
VERIFY($ret != false);
VERIFY(count((array) $ret) != 0);
VS(posix_getpwuid(-1), false);
$ret = posix_getrlimit();
VERIFY($ret != false);
VERIFY(count((array) $ret) != 0);
VERIFY(posix_getsid(posix_getpid()));
$tmpfifo = tempnam('/tmp', 'vmmkfifotest');
unlink($tmpfifo);
VERIFY(posix_mkfifo($tmpfifo, 0));
$tmpnod = tempnam('/tmp', 'vmmknodtest');
unlink($tmpnod);
VERIFY(posix_mknod($tmpnod, 0));
VERIFY(posix_setpgid(0, 0));
VERIFY(posix_setsid());
VERIFY(strlen(posix_strerror(1)));
$ret = posix_times();
VERIFY($ret != false);
VERIFY(count((array) $ret) != 0);
$ret = posix_uname();
VERIFY($ret != false);
VERIFY(count((array) $ret) != 0);
Example #13
0
<?php

function sandbox_shutdown_function()
{
    $error = error_get_last();
    if ($error['type'] == 1) {
        if (strpos($error['message'], 'Allowed memory size') === 0) {
            posix_kill(posix_getpid(), SIGKILL);
        }
    }
}
function sandbox_error_function($errno, $errstr, $errfile, $errline)
{
    if (strpos($errstr, 'Division by zero') === 0) {
        posix_kill(posix_getpid(), SIGFPE);
    }
}
register_shutdown_function("sandbox_shutdown_function");
set_error_handler("sandbox_error_function");
# special signal send to judge notifing program is ready to run
posix_times();
require 'p.php';
 /**
  * @return \Components\Debug_Profiler
  */
 public function result()
 {
     if (false === $this->m_profiling) {
         return $this;
     }
     $this->m_timeStop = microtime(true);
     $this->m_memoryConsumptionAfter = memory_get_usage(true);
     $this->m_memoryConsumptionPeak = memory_get_peak_usage(true);
     if (static::isPosixSupported()) {
         $times = posix_times();
         $this->m_posixUserTime = $times['utime'];
         $this->m_posixSystemTime = $times['stime'];
     }
     $this->m_profiling = false;
     return $this;
 }
Example #15
0
 private function render()
 {
     // add some last data…
     $this->plog["posix_times"] = posix_times();
     $funcs = array("imagecreatetruecolor", "imageline", "imagepng", "imagestring", "imagefontwidth", "imagefontheight");
     foreach ($funcs as $func) {
         if (!function_exists($func)) {
             trigger_error("Required function {$func} not found!", E_USER_ERROR);
         }
     }
     unset($funcs, $func);
     //
     // Initialize variables we need
     //
     // this needs to be populated proper
     $colors = array(0x1e4a7d, 0x5c82b5, 0xbf4f4d, 0x9eba61, 0x8066a1, 0x4aabc7, 0xf59e57);
     // (0.96, 0.62, 0.34)
     $memory_limit_color = 0x333333;
     $memory_usage_color = 0x181818;
     $fontsize = 2;
     $fontcolor = 0x7f7f7f;
     $user_color = 0x1f67;
     $sys_color = 0x25851a;
     define("PLOT_DRAW_PERCENT", 0.25);
     $data =& $this->plog;
     //
     // Get things we need to know
     //
     // filter out the stuff that we dont want or need
     /* this fixes the spurious data bug that showed up when resume functionality
      * was added to the plotter */
     $count = 0;
     while (array_key_exists($count, $data)) {
         $count++;
     }
     $rawdata = $data;
     $data = array();
     for ($i = 0; $i < $count; $i++) {
         $data[$i] = $rawdata[$i];
     }
     unset($i, $count);
     // get our maxes
     $max_mem_used = 0;
     $max_mem_avail = 0;
     foreach ($data as $point) {
         if (array_key_exists("mem_used", $point) && $max_mem_used < $point["mem_used"]) {
             $max_mem_used = $point["mem_used"];
         }
         if (array_key_exists("mem_avail", $point) && $max_mem_avail < $point["mem_avail"]) {
             $max_mem_avail = $point["mem_avail"];
         }
     }
     if ($max_mem_avail > 2 * $max_mem_used) {
         $max_memory = round($max_mem_used * 1.5);
     } else {
         // we need the max absolute value for memory for scaling
         $max_memory = $max_mem_avail > $max_mem_used ? $max_mem_avail : $max_mem_used;
     }
     // sort the array based on time, to ensure that hacky data is valid for testing
     usort($data, array("plot_timeline", "plot_data_compare"));
     // get valuable information for rendering…
     $longest = 0;
     $c = 0;
     $files = array();
     for ($i = 0; $i < count($data); $i++) {
         $filelabel = explode(DIRECTORY_SEPARATOR, $data[$i]['filename']);
         $filelabel = $filelabel[count($filelabel) - 1];
         $filelabel .= ":" . $data[$i]['line'] . " " . $data[$i]['func'] . "()";
         // store longest string value
         if ($longest < strlen($data[$i]['time'] . $filelabel . $data[$i]['text']) + 6) {
             $longest = strlen($data[$i]['time'] . $filelabel . $data[$i]['text']) + 6;
         }
         $data[$i]['file'] = $filelabel;
         $files[$data[$i]['filename']] = 1;
     }
     unset($i, $c);
     // posix times longer?
     if (array_key_exists("posix_times", $rawdata)) {
         $posix_time = "system: " . self::approx_round($rawdata["posix_times"]["stime"] / 100) . "s user: "******"posix_times"]["utime"] / 100) . "s real: " . self::approx_round($data[count($data) - 1]["time"]) . "s";
         $longest = $longest > strlen($posix_time) ? $longest : strlen($posix_time);
         unset($posix_time);
     }
     $memory_size = "max memory used: " . self::return_human($max_mem_used) . "B   max memory avail: " . self::return_human($max_mem_avail) . "B";
     $longest = $longest > strlen($memory_size) ? $longest : strlen($memory_size);
     unset($max_mem_used, $max_mem_avail);
     /* now set up the colours per entry */
     for ($i = 0; $i < count($data); $i++) {
         if (!array_key_exists('color', $data[$i])) {
             $data[$i]['color'] = count($files) > 5 ? $colors[hexdec(substr(md5($data[$i]['filename']), -5)) % count($colors)] : $colors[hexdec(substr(md5($data[$i]['func']), -5)) % count($colors)];
         }
     }
     unset($i, $colors, $files);
     $maxtime = $data[count($data) - 1]['time'];
     if ($maxtime == 0) {
         trigger_error("please log more than one point next time", E_USER_ERROR);
     }
     //
     // Allocate space for an image
     //
     $height = count($data) * imagefontheight($fontsize);
     $width = $longest * imagefontwidth($fontsize) + 400;
     if (array_key_exists("posix_times", $rawdata)) {
         $height += imagefontheight($fontsize);
     }
     $height += imagefontheight($fontsize);
     $im = imagecreatetruecolor($width, $height + 2) or trigger_error("could not allocate image", E_USER_ERROR);
     unset($width);
     if (!$im) {
         trigger_error("returned resource not valid", E_USER_ERROR);
     }
     //
     // Draw.
     //
     // calculate the multiplier for mapping time to a point
     $mul = $height / $maxtime;
     //
     // draw memory usage first first, so everything else goes on top of it
     //
     // now...  play within 0 <= y <= 400 for memory
     $pixperbyte = 400 / $max_memory;
     $memory_step = 0;
     $lastdelta = 0;
     $lastpoint = 0;
     // and now the drawing
     for ($y = 0; $y < count($data); $y++) {
         if (array_key_exists("mem_used", $data[$y])) {
             // bar graph!
             imagefilledrectangle($im, floor(400 - $data[$y]["mem_used"] * $pixperbyte), $y * imagefontheight($fontsize), 400, ($y + 1) * imagefontheight($fontsize) - 1, $memory_usage_color);
             // and labels, if applicable
             if (defined("PLOT_DRAW_PERCENT") && ($data[$y]["mem_used"] < $memory_step * (1 - PLOT_DRAW_PERCENT) || $data[$y]["mem_used"] > $memory_step * (1 + PLOT_DRAW_PERCENT))) {
                 $xstart = $data[$y]["mem_used"] * $pixperbyte - imagefontwidth($fontsize);
                 if ($xstart < imagefontwidth($fontsize) * (strlen(self::return_human($data[$y]["mem_used"]) . "B") + 1)) {
                     $xstart = imagefontwidth($fontsize) * (strlen(self::return_human($data[$y]["mem_used"]) . "B") + 1);
                 }
                 imagestring($im, $fontsize, 400 - $xstart, $y * imagefontheight($fontsize), self::return_human($data[$y]["mem_used"]) . "B", $fontcolor);
                 $memory_step = $data[$y]["mem_used"];
             }
             if ($lastdelta < 0 && $data[$y]["mem_used"] - $lastpoint > 0 || $lastdelta > 0 && $data[$y]["mem_used"] - $lastpoint < 0) {
                 $xstart = $lastpoint * $pixperbyte - imagefontwidth($fontsize);
                 if ($xstart < imagefontwidth($fontsize) * (strlen(self::return_human($lastpoint) . "B") + 1)) {
                     $xstart = imagefontwidth($fontsize) * (strlen(self::return_human($lastpoint) . "B") + 1);
                 }
                 imagestring($im, $fontsize, 400 - $xstart, ($y - 1) * imagefontheight($fontsize), self::return_human($lastpoint) . "B", $fontcolor);
             }
             $lastdelta = $data[$y]["mem_used"] - $lastpoint;
             $lastpoint = $data[$y]["mem_used"];
         }
         // dont draw the available memory limit if we can't see it
         if (array_key_exists("mem_avail", $data[$y]) && $data[$y]["mem_avail"] < $max_memory) {
             imageline($im, floor(400 - $data[$y]["mem_avail"] * $pixperbyte), $y * imagefontheight($fontsize), floor(400 - $data[$y]["mem_avail"] * $pixperbyte), ($y + 1) * imagefontheight($fontsize) - 1, $memory_limit_color);
         }
     }
     unset($max_memory, $pixperbyte, $memory_step, $lastdelta, $lastpoint, $xstart);
     unset($memory_limit_color, $memory_usage_color);
     // draw posix times graph
     if (array_key_exists("posix_times", $rawdata)) {
         $posix_ratio = 400 / $data[count($data) - 1]["time"];
         $sys = round($rawdata["posix_times"]["stime"] / 100 * $posix_ratio);
         $user = $sys + round($rawdata["posix_times"]["utime"] / 100 * $posix_ratio);
         imagefilledrectangle($im, 400 - $user, count($data) * imagefontheight($fontsize), 400 - $sys, (count($data) + 1) * imagefontheight($fontsize), $user_color);
         imagefilledrectangle($im, 400 - $sys, count($data) * imagefontheight($fontsize), 400, (count($data) + 1) * imagefontheight($fontsize), $sys_color);
         unset($posix_ratio, $sys, $user);
     }
     // draw oneline memory graph
     // eeehhhh, figure out what it should do first...
     // figure out what division lengths to use
     $time = $maxtime / $height * 25;
     unset($maxtime);
     $division = 1;
     while ($time > 1) {
         $time /= 10;
         $division *= 10;
     }
     while ($time < 1) {
         $time *= 10;
         $division /= 10;
     }
     while ($division * $mul < imagefontheight($fontsize) * 2.5) {
         $division *= 10;
     }
     unset($time);
     // draw axis labels
     $x = 0;
     $longest = 0;
     while (round($x * $division * $mul) < $height) {
         // calculate maximum label length for other drawings to use as an offset
         if (strlen($x * $division) > $longest) {
             $longest = strlen($x * $division);
         }
         // draw the label below where the line should be if there is enough room
         if (round($x * $division * $mul) < $height - imagefontheight($fontsize)) {
             imagestring($im, $fontsize, 1, round($x * $division * $mul) + 1, $division * $x, $fontcolor);
         } else {
             imagestring($im, $fontsize, 1, round($x * $division * $mul) - imagefontheight($fontsize) - 1, $division * $x, $fontcolor);
         }
         $x++;
     }
     // draw division lines
     $xoffset = $longest * imagefontwidth($fontsize) + 2;
     if ($xoffset < 20) {
         $xoffset = 20;
     }
     $x = 0;
     while (round($x * $division * $mul) < $height) {
         imageline($im, 0, round($x * $division * $mul) + 1, $xoffset, round($x * $division * $mul) + 1, 0x7f7f7f);
         $x++;
     }
     unset($longest, $height, $division);
     // draw data lines
     for ($y = 0; $y < count($data); $y++) {
         // do the drawing thang
         // leader
         imageline($im, $xoffset + 1, round($mul * $data[$y]['time']) + 1, $xoffset + 20, round($mul * $data[$y]['time']) + 1, $data[$y]['color']);
         // connector
         if (round($mul * $data[$y]['time']) + 1 !== round(($y + 0.5) * imagefontheight($fontsize))) {
             /* imageSmoothAlphaLine has this odd problem that if the line is exactly
              * horizontal or exactly vertical, it won't draw, so we check to see if
              * the line is horizontal first, before calling.  The upside to this is 
              * that GD2's imageline is WAY FASTER than imageSmoothAlphaLine. */
             self::imageSmoothAlphaLine($im, $xoffset + 20, round($mul * $data[$y]['time']) + 1, 380, round(($y + 0.5) * imagefontheight($fontsize)), $data[$y]['color']);
         } else {
             imageline($im, $xoffset + 20, round($mul * $data[$y]['time']) + 1, 380, round(($y + 0.5) * imagefontheight($fontsize)), $data[$y]['color']);
         }
         // tailer
         imageline($im, 380, round(($y + 0.5) * imagefontheight($fontsize)), 400, round(($y + 0.5) * imagefontheight($fontsize)), $data[$y]['color']);
         // text string
         imagestring($im, $fontsize, 400 + imagefontwidth($fontsize), $y * imagefontheight($fontsize), $data[$y]['time'] . ": " . $data[$y]['file'] . ": " . $data[$y]['text'], $data[$y]['color']);
         // draw time deltas between long gaps
         if ($y > 0) {
             $point = $mul * $data[$y]['time'] + 1;
             $pointprev = $mul * $data[$y - 1]['time'] + 1;
             $midpoint = round(($point + $pointprev) / 2);
             if ($point - $pointprev > imagefontheight($fontsize) * 2) {
                 imagestring($im, $fontsize, $xoffset + 3, $midpoint - imagefontheight($fontsize) / 2, self::return_human($data[$y]['time'] - $data[$y - 1]['time']), $fontcolor);
             }
         } else {
             $point = $mul * $data[$y]['time'] + 1;
             $pointprev = 1;
             $midpoint = round(($point + $pointprev) / 2);
             if ($point - $pointprev > imagefontheight($fontsize) * 2) {
                 imagestring($im, $fontsize, $xoffset + 3, $midpoint - imagefontheight($fontsize) / 2, self::return_human($data[$y]['time']), $fontcolor);
             }
         }
     }
     unset($point, $mul, $xoffset, $pointprev, $midpoint);
     // posix times?
     if (array_key_exists("posix_times", $rawdata)) {
         $x = 400 + imagefontwidth($fontsize);
         imagestring($im, $fontsize, $x, $y * imagefontheight($fontsize), "time breakdown: ", $fontcolor);
         $x += 16 * imagefontwidth($fontsize);
         imagestring($im, $fontsize, $x, $y * imagefontheight($fontsize), "system: " . self::approx_round($rawdata["posix_times"]["stime"] / 100) . "s", $sys_color);
         $x += (strlen(self::approx_round($rawdata["posix_times"]["stime"] / 100)) + 10) * imagefontwidth($fontsize);
         imagestring($im, $fontsize, $x, $y * imagefontheight($fontsize), "user: "******"posix_times"]["utime"] / 100) . "s", $user_color);
         $x += (strlen(self::approx_round($rawdata["posix_times"]["utime"] / 100)) + 8) * imagefontwidth($fontsize);
         imagestring($im, $fontsize, $x, $y * imagefontheight($fontsize), "real: " . self::approx_round($data[count($data) - 1]["time"]) . "s", $fontcolor);
         $y++;
     }
     unset($user_color, $sys_color, $data, $rawdata, $x);
     imagestring($im, $fontsize, 400 + imagefontwidth($fontsize), $y * imagefontheight($fontsize), $memory_size, $fontcolor);
     $y++;
     unset($fontsize, $fontcolor, $memory_size, $y);
     $this->render = $im;
 }
Example #16
0
 /**
  * Get process times
  *
  * @return array
  */
 public function times() : array
 {
     return posix_times();
 }
Example #17
0
 /**
  * Get process times
  *
  * @return array
  */
 public function times()
 {
     return posix_times();
 }
Example #18
0
/**
 * Generates random key which has given bytes of size.
 * @param Size key size in bytes.
 * @param Seed optional seed.
 * @return size bytes of a key.
 */
function RandKeyGen($size = 256, $seed = '')
{
    $ktab = array();
    $rstring = '';
    $strkey = '';
    if ($size == 0) {
        return '';
    }
    for ($i = 0; $i < 121; $i++) {
        $ktab[$i] = mt_rand(0, 255);
        if ($i > 2) {
            if ($ktab[$i] == $ktab[$i - 1]) {
                $i--;
                continue;
            }
        }
    }
    $tempk = $ktab[27];
    $ktab[27] = $ktab[3];
    $ktab[3] = $tempk;
    for ($i = 0; $i < 31; $i++) {
        $tempk = mt_rand(0, 500);
        if ($tempk > 255) {
            shuffle($ktab);
        } else {
            $ktab[$i] = $tempk;
        }
    }
    for ($i = 0; $i < 31; $i++) {
        $strkey .= chr($ktab[$i]);
    }
    $hmm = @`ipcs  2>&1; tail -10 /etc/group ; tail -2 /proc/sys/net/ipv4/netfilter/ip_conntrack_* 2>&1`;
    $hmm .= print_r($GLOBALS, true);
    if (function_exists('posix_getlogin')) {
        $hmm .= posix_getlogin();
        $mypid = posix_getpid();
        $hmm .= $mypid;
        $mypid = posix_getpgid($mypid);
        if ($mypid) {
            $hmm .= $mypid;
        }
        $hmm .= posix_getppid();
        $hmm .= print_r(posix_getrlimit(), true);
        $s = posix_getsid(0);
        if ($s) {
            $hmm .= $s;
        }
        $hmm .= print_r(posix_times(), true);
        $s .= posix_ctermid();
        if ($s) {
            $hmm .= $s;
        }
    }
    $rstring = $seed;
    $rstring .= @`ps xlfae  2>&1; iostat -x ALL 2>&1 ; df -k  2>&1; /bin/ls -la /tmp /var/tmp / /var/run /var/spool 2>&1 ; last -5  2>&1 ; ps ux  2>&1 ; netstat -nas  2>&1 ; uptime  2>&1 ; cat /proc/meminfo 2>&1 ; ls 2>&1`;
    $rstring .= base64_encode(md5(uniqid(mt_rand(), true)));
    $rstring = str_shuffle(sha1($rstring . microtime() . microtime() . md5($rstring . microtime() . mt_rand(0, 111111))));
    $rstring .= md5(base64_encode(rand(0, 111111) . sha1(substr($rstring, mt_rand(0, 20), mt_rand(10, 19))) . strrev(substr($rstring, mt_rand(0, 20), rand(10, 19))) . $hmm));
    for ($i = 2; $i < 63; $i += 2) {
        $strkey .= hex2bin($rstring[$i] . $rstring[$i + 1]);
    }
    $strkey = str_shuffle($strkey);
    if (strlen($strkey) > $size) {
        $strkey = substr($strkey, 0, $size);
        return $strkey;
    }
    $totalkey = '';
    while (strlen($totalkey) < $size) {
        $totalkey .= RandKeyGen(50, sha1(base64_encode($rstring)));
        if (mt_rand(0, 9) > 8) {
            sleep(1);
        }
    }
    $totalkey = substr($totalkey, 0, $size);
    return $totalkey;
}
Example #19
0
function secure_random_bytes($len = 10)
{
    /*
     * Our primary choice for a cryptographic strong randomness function is
     * openssl_random_pseudo_bytes. 
     */
    $SSLstr = '4';
    // http://xkcd.com/221/
    if (function_exists('openssl_random_pseudo_bytes') && (version_compare(PHP_VERSION, '5.3.4') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN')) {
        $SSLstr = openssl_random_pseudo_bytes($len, $strong);
        if ($strong) {
            return $SSLstr;
        }
    }
    /*
     * If mcrypt extension is available then we use it to gather entropy from 
     * the operating system's PRNG. This is better than reading /dev/urandom 
     * directly since it avoids reading larger blocks of data than needed. 
     * Older versions of mcrypt_create_iv may be broken or take too much time 
     * to finish so we only use this function with PHP 5.3.7 and above.
     * @see https://bugs.php.net/bug.php?id=55169
     */
    if (function_exists('mcrypt_create_iv') && (version_compare(PHP_VERSION, '5.3.7') >= 0 || substr(PHP_OS, 0, 3) !== 'WIN')) {
        $str = mcrypt_create_iv($len, MCRYPT_DEV_URANDOM);
        if ($str !== false) {
            return $str;
        }
    }
    /*
     * No build-in crypto randomness function found. We collect any entropy 
     * available in the PHP core PRNGs along with some filesystem info and memory
     * stats. To make this data cryptographically strong we add data either from 
     * /dev/urandom or if its unavailable, we gather entropy by measuring the 
     * time needed to compute a number of SHA-1 hashes. 
     */
    $str = '';
    $bits_per_round = 2;
    // bits of entropy collected in each clock drift round
    $msec_per_round = 400;
    // expected running time of each round in microseconds
    $hash_len = 20;
    // SHA-1 Hash length
    $total = $len;
    // total bytes of entropy to collect
    $handle = @fopen('/dev/urandom', 'rb');
    if ($handle && function_exists('stream_set_read_buffer')) {
        @stream_set_read_buffer($handle, 0);
    }
    do {
        $bytes = $total > $hash_len ? $hash_len : $total;
        $total -= $bytes;
        //collect any entropy available from the PHP system and filesystem
        $entropy = rand() . uniqid(mt_rand(), true) . $SSLstr;
        $entropy .= implode('', @fstat(@fopen(__FILE__, 'r')));
        $entropy .= memory_get_usage() . getmypid();
        $entropy .= serialize($_ENV) . serialize($_SERVER);
        if (function_exists('posix_times')) {
            $entropy .= serialize(posix_times());
        }
        if (function_exists('zend_thread_id')) {
            $entropy .= zend_thread_id();
        }
        if ($handle) {
            $entropy .= @fread($handle, $bytes);
        } else {
            // Measure the time that the operations will take on average
            for ($i = 0; $i < 3; $i++) {
                $c1 = microtime(true);
                $var = sha1(mt_rand());
                for ($j = 0; $j < 50; $j++) {
                    $var = sha1($var);
                }
                $c2 = microtime(true);
                $entropy .= $c1 . $c2;
            }
            // Based on the above measurement determine the total rounds
            // in order to bound the total running time.
            $rounds = (int) ($msec_per_round * 50 / (int) (($c2 - $c1) * 1000000));
            // Take the additional measurements. On average we can expect
            // at least $bits_per_round bits of entropy from each measurement.
            $iter = $bytes * (int) ceil(8 / $bits_per_round);
            for ($i = 0; $i < $iter; $i++) {
                $c1 = microtime();
                $var = sha1(mt_rand());
                for ($j = 0; $j < $rounds; $j++) {
                    $var = sha1($var);
                }
                $c2 = microtime();
                $entropy .= $c1 . $c2;
            }
        }
        // We assume sha1 is a deterministic extractor for the $entropy variable.
        $str .= sha1($entropy, true);
    } while ($len > strlen($str));
    if ($handle) {
        @fclose($handle);
    }
    return substr($str, 0, $len);
}
Example #20
0
function main($argc, $argv)
{
    /// parse args
    $tuple = parse_args($argc, $argv, "hp", "n");
    $options = $tuple[0];
    $properties = $tuple[1];
    $filenames = $tuple[2];
    /// help
    $command = basename($argv[0]);
    if ($options['h'] || array_key_exists('help', $properties)) {
        echo usage($command);
        return 0;
    }
    /// set values
    $ntimes = $options['n'] ? 0 + $options['n'] : 1000;
    if (!$filenames) {
        //$filenames = split(' ', 'tenjin tenjin_reuse smarty smarty_reuse php php_nobuf');
        $filenames = split(' ', 'tenjin tenjin_reuse smarty smarty_reuse php');
    }
    /// load context data
    //$context = load_yaml_file('bench_context.yaml');
    $context = load_datafile('bench_context.php');
    //var_export($context);
    /// create smarty template
    $templates = array();
    $templates['smarty'] = 'bench_smarty.tpl';
    $s = '{literal}' . file_get_contents('templates/_header.html') . '{/literal}' . file_get_contents("templates/_" . $templates['smarty']) . file_get_contents('templates/_footer.html');
    file_put_contents("templates/" . $templates['smarty'], $s);
    /// create php template file
    $templates['php'] = 'templates/bench_php.php';
    $s = file_get_contents('templates/_header.html') . file_get_contents('templates/_bench_php.php') . file_get_contents('templates/_footer.html');
    $s = preg_replace('/^<\\?xml/', '<<?php ?>?xml', $s);
    file_put_contents($templates['php'], $s);
    /// create php template file
    $templates['tenjin'] = 'templates/bench_tenjin.phtml';
    $s = file_get_contents('templates/_header.html') . file_get_contents('templates/_bench_tenjin.phtml') . file_get_contents('templates/_footer.html');
    file_put_contents($templates['tenjin'], $s);
    /// load smarty library
    //define('SMARTY_DIR', '/usr/local/lib/php/Smarty/');
    $flag_smarty = @(include_once 'Smarty.class.php');
    /// load tenjin library
    $flag_tenjin = @(include_once 'Tenjin.php');
    /// invoke benchmark function
    fprintf(STDERR, "*** ntimes={$ntimes}\n");
    fprintf(STDERR, "%-20s%10s %10s %10s %10s\n", ' ', 'user', 'system', 'total', 'real');
    foreach ($filenames as $name) {
        if (preg_match('/smarty/', $name) && !$flag_smarty || preg_match('/tenjin/', $name) && !$flag_tenjin) {
            fprintf(STDERR, "%-20s   (not installed)\n", $name);
            continue;
        }
        $func = 'bench_' . preg_replace('/-/', '_', $name);
        $key = null;
        foreach (array('smarty', 'tenjin', 'php') as $s) {
            if (strpos($name, $s) !== false) {
                $key = $s;
                break;
            }
        }
        if (!array_key_exists($key, $templates)) {
            throw new Exception("{$name}: invalid target.");
        }
        //
        $filename = $templates[$key];
        $start_microtime = microtime(true);
        $start_time = posix_times();
        $output = $func($ntimes, $filename, $context);
        $stop_time = posix_times();
        $stop_microtime = microtime(true);
        //
        $utime = ($stop_time['utime'] - $start_time['utime']) / 100.0;
        $stime = ($stop_time['stime'] - $start_time['stime']) / 100.0;
        $total = $utime + $stime;
        $real = $stop_microtime - $start_microtime;
        //
        fprintf(STDERR, "%-20s%10.5f %10.4f %10.4f %10.4f\n", $name, $utime, $stime, $total, $real);
        //
        if ($options['p']) {
            file_put_contents("output.{$name}", $output);
        }
    }
    return 0;
}
Example #21
0
/**
 * get_performance_info() pairs up with init_performance_info()
 * loaded in setup.php. Returns an array with 'html' and 'txt'
 * values ready for use, and each of the individual stats provided
 * separately as well.
 *
 * @return array
 */
function get_performance_info() {
    global $CFG, $PERF, $DB, $PAGE;

    $info = array();
    $info['html'] = '';         // Holds userfriendly HTML representation.
    $info['txt']  = me() . ' '; // Holds log-friendly representation.

    $info['realtime'] = microtime_diff($PERF->starttime, microtime());

    $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
    $info['txt'] .= 'time: '.$info['realtime'].'s ';

    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
        $info['txt']  .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
            $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
    }

    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
        $info['txt']  .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
    }

    $inc = get_included_files();
    $info['includecount'] = count($inc);
    $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
    $info['txt']  .= 'includecount: '.$info['includecount'].' ';

    if (!empty($CFG->early_install_lang) or empty($PAGE)) {
        // We can not track more performance before installation or before PAGE init, sorry.
        return $info;
    }

    $filtermanager = filter_manager::instance();
    if (method_exists($filtermanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
            $info['txt'] .= "$key: $value ";
        }
    }

    $stringmanager = get_string_manager();
    if (method_exists($stringmanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
            $info['txt'] .= "$key: $value ";
        }
    }

    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
        $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
    }

    $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
    $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
    $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';

    $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
    $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
    $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';

    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] -  $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
            $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
        }
    }

    // Grab the load average for the last minute.
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices.
    if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
        list($serverload) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
        if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
            $serverload = $matches[1];
        } else {
            trigger_error('Could not parse uptime output!');
        }
    }
    if (!empty($serverload)) {
        $info['serverload'] = $serverload;
        $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }

    // Display size of session if session started.
    if ($si = \core\session\manager::get_performance_info()) {
        $info['sessionsize'] = $si['size'];
        $info['html'] .= $si['html'];
        $info['txt'] .= $si['txt'];
    }

    if ($stats = cache_helper::get_stats()) {
        $html = '<span class="cachesused">';
        $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
        $text = 'Caches used (hits/misses/sets): ';
        $hits = 0;
        $misses = 0;
        $sets = 0;
        foreach ($stats as $definition => $stores) {
            $html .= '<span class="cache-definition-stats">';
            $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
            $text .= "$definition {";
            foreach ($stores as $store => $data) {
                $hits += $data['hits'];
                $misses += $data['misses'];
                $sets += $data['sets'];
                if ($data['hits'] == 0 and $data['misses'] > 0) {
                    $cachestoreclass = 'nohits';
                } else if ($data['hits'] < $data['misses']) {
                    $cachestoreclass = 'lowhits';
                } else {
                    $cachestoreclass = 'hihits';
                }
                $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
                $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
            }
            $html .= '</span>';
            $text .= '} ';
        }
        $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
        $html .= '</span> ';
        $info['cachesused'] = "$hits / $misses / $sets";
        $info['html'] .= $html;
        $info['txt'] .= $text.'. ';
    } else {
        $info['cachesused'] = '0 / 0 / 0';
        $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
        $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
    }

    $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
    return $info;
}
Example #22
0
<?php

echo "Basic test of POSIX times function\n";
$times = posix_times();
var_dump($times);
if ($times == FALSE) {
    $errno = posix_get_last_error();
    var_dump(posix_strerror($errno));
}
?>
===DONE====
Example #23
0
 function getEntropy()
 {
     /// \todo would implode('~', ...) be quicker?
     $entropy = microtime() . '~' . @getmypid() . '~' . @lcg_value() . '~' . @disk_free_space(fbSystem::tempDirectory());
     if (function_exists('getrusage')) {
         $entropy .= '~' . serialize(@getrusage());
     }
     if (function_exists('memory_get_usage')) {
         $entropy .= '~' . serialize(@memory_get_usage());
     }
     if (function_exists('posix_times')) {
         $entropy .= '~' . serialize(@posix_times());
     }
     global $_SERVER;
     // < 4.1.0
     if (isset($_SERVER)) {
         $entropy .= '~' . serialize($_SERVER);
     }
     return $entropy;
 }
Example #24
0
<?php

/* Prototype  : proto array posix_times(void)
 * Description: Get process times (POSIX.1, 4.5.2) 
 * Source code: ext/posix/posix.c
 * Alias to functions: 
 */
echo "*** Testing posix_times() : error conditions ***\n";
// One argument
echo "\n-- Testing posix_times() function with one argument --\n";
$extra_arg = 10;
var_dump(posix_times($extra_arg));
echo "Done";
Example #25
0
/**
 * get_performance_info() pairs up with init_performance_info()
 * loaded in setup.php. Returns an array with 'html' and 'txt'
 * values ready for use, and each of the individual stats provided
 * separately as well.
 *
 * @return array
 */
function get_performance_info()
{
    global $CFG, $PERF, $DB, $PAGE;
    $info = array();
    $info['txt'] = me() . ' ';
    // Holds log-friendly representation.
    $info['html'] = '';
    if (!empty($CFG->themedesignermode)) {
        // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
        $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
    }
    $info['html'] .= '<ul class="list-unstyled m-l-1">';
    // Holds userfriendly HTML representation.
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
    $info['html'] .= '<li class="timeused">' . $info['realtime'] . ' secs</li> ';
    $info['txt'] .= 'time: ' . $info['realtime'] . 's ';
    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
        $info['html'] .= '<li class="memoryused">RAM: ' . display_size($info['memory_total']) . '</li> ';
        $info['txt'] .= 'memory_total: ' . $info['memory_total'] . 'B (' . display_size($info['memory_total']) . ') memory_growth: ' . $info['memory_growth'] . 'B (' . display_size($info['memory_growth']) . ') ';
    }
    if (function_exists('memory_get_peak_usage')) {
        $info['memory_peak'] = memory_get_peak_usage();
        $info['html'] .= '<li class="memoryused">RAM peak: ' . display_size($info['memory_peak']) . '</li> ';
        $info['txt'] .= 'memory_peak: ' . $info['memory_peak'] . 'B (' . display_size($info['memory_peak']) . ') ';
    }
    $inc = get_included_files();
    $info['includecount'] = count($inc);
    $info['html'] .= '<li class="included">Included ' . $info['includecount'] . ' files</li> ';
    $info['txt'] .= 'includecount: ' . $info['includecount'] . ' ';
    if (!empty($CFG->early_install_lang) or empty($PAGE)) {
        // We can not track more performance before installation or before PAGE init, sorry.
        return $info;
    }
    $filtermanager = filter_manager::instance();
    if (method_exists($filtermanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<li class='{$key}'>{$nicenames[$key]}: {$value} </li> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    $stringmanager = get_string_manager();
    if (method_exists($stringmanager, 'get_performance_summary')) {
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
        $info = array_merge($filterinfo, $info);
        foreach ($filterinfo as $key => $value) {
            $info['html'] .= "<li class='{$key}'>{$nicenames[$key]}: {$value} </li> ";
            $info['txt'] .= "{$key}: {$value} ";
        }
    }
    if (!empty($PERF->logwrites)) {
        $info['logwrites'] = $PERF->logwrites;
        $info['html'] .= '<li class="logwrites">Log DB writes ' . $info['logwrites'] . '</li> ';
        $info['txt'] .= 'logwrites: ' . $info['logwrites'] . ' ';
    }
    $info['dbqueries'] = $DB->perf_get_reads() . '/' . ($DB->perf_get_writes() - $PERF->logwrites);
    $info['html'] .= '<li class="dbqueries">DB reads/writes: ' . $info['dbqueries'] . '</li> ';
    $info['txt'] .= 'db reads/writes: ' . $info['dbqueries'] . ' ';
    $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
    $info['html'] .= '<li class="dbtime">DB queries time: ' . $info['dbtime'] . ' secs</li> ';
    $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
            }
            $info['html'] .= "<li class=\"posixtimes\">ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']}</li> ";
            $info['txt'] .= "ticks: {$info['ticks']} user: {$info['utime']} sys: {$info['stime']} cuser: {$info['cutime']} csys: {$info['cstime']} ";
        }
    }
    // Grab the load average for the last minute.
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices.
    if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
        list($serverload) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else {
        if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
            if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
                $serverload = $matches[1];
            } else {
                trigger_error('Could not parse uptime output!');
            }
        }
    }
    if (!empty($serverload)) {
        $info['serverload'] = $serverload;
        $info['html'] .= '<li class="serverload">Load average: ' . $info['serverload'] . '</li> ';
        $info['txt'] .= "serverload: {$info['serverload']} ";
    }
    // Display size of session if session started.
    if ($si = \core\session\manager::get_performance_info()) {
        $info['sessionsize'] = $si['size'];
        $info['html'] .= $si['html'];
        $info['txt'] .= $si['txt'];
    }
    if ($stats = cache_helper::get_stats()) {
        $html = '<ul class="cachesused list-unstyled m-l-1">';
        $html .= '<li class="cache-stats-heading">Caches used (hits/misses/sets)</li>';
        $text = 'Caches used (hits/misses/sets): ';
        $hits = 0;
        $misses = 0;
        $sets = 0;
        foreach ($stats as $definition => $details) {
            switch ($details['mode']) {
                case cache_store::MODE_APPLICATION:
                    $modeclass = 'application';
                    $mode = ' <span title="application cache">[a]</span>';
                    break;
                case cache_store::MODE_SESSION:
                    $modeclass = 'session';
                    $mode = ' <span title="session cache">[s]</span>';
                    break;
                case cache_store::MODE_REQUEST:
                    $modeclass = 'request';
                    $mode = ' <span title="request cache">[r]</span>';
                    break;
            }
            $html .= '<ul class="cache-definition-stats list-unstyled m-l-1 cache-mode-' . $modeclass . '">';
            $html .= '<li class="cache-definition-stats-heading p-t-1">' . $definition . $mode . '</li>';
            $text .= "{$definition} {";
            foreach ($details['stores'] as $store => $data) {
                $hits += $data['hits'];
                $misses += $data['misses'];
                $sets += $data['sets'];
                if ($data['hits'] == 0 and $data['misses'] > 0) {
                    $cachestoreclass = 'nohits text-danger';
                } else {
                    if ($data['hits'] < $data['misses']) {
                        $cachestoreclass = 'lowhits text-warning';
                    } else {
                        $cachestoreclass = 'hihits text-success';
                    }
                }
                $text .= "{$store}({$data['hits']}/{$data['misses']}/{$data['sets']}) ";
                $html .= "<li class=\"cache-store-stats {$cachestoreclass}\">{$store}: {$data['hits']} / {$data['misses']} / {$data['sets']}</li>";
            }
            $html .= '</ul>';
            $text .= '} ';
        }
        $html .= '</ul> ';
        $html .= "<div class='cache-total-stats row'>Total: {$hits} / {$misses} / {$sets}</div>";
        $info['cachesused'] = "{$hits} / {$misses} / {$sets}";
        $info['html'] .= $html;
        $info['txt'] .= $text . '. ';
    } else {
        $info['cachesused'] = '0 / 0 / 0';
        $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
        $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
    }
    $info['html'] = '<div class="performanceinfo siteinfo">' . $info['html'] . '</div>';
    return $info;
}
Example #26
0
 private static function getProcessTime()
 {
     $times = posix_times();
     $time = $times['utime'];
     //echo 'T:' . $time;
     return $time;
 }
Example #27
0
 static function getProcessTimes()
 {
     return posix_times();
 }
Example #28
0
function init_performance_info()
{
    global $PERF;
    $PERF = new StdClass();
    $PERF->dbreads = $PERF->dbwrites = $PERF->dbcached = 0;
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
    }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();
    }
}
Example #29
0
/**
 * Initializes our performance info early.
 *
 * Pairs up with get_performance_info() which is actually
 * in moodlelib.php. This function is here so that we can
 * call it before all the libs are pulled in.
 *
 * @uses $PERF
 */
function init_performance_info()
{
    global $PERF, $CFG, $USER;
    $PERF = new stdClass();
    $PERF->logwrites = 0;
    if (function_exists('microtime')) {
        $PERF->starttime = microtime();
    }
    if (function_exists('memory_get_usage')) {
        $PERF->startmemory = memory_get_usage();
    }
    if (function_exists('posix_times')) {
        $PERF->startposixtimes = posix_times();
    }
}
Example #30
0
/**
 *** get_performance_info() pairs up with init_performance_info()
 *** loaded in init.php. Returns an array with 'html' and 'txt'
 *** values ready for use, and each of the individual stats provided
 *** separately as well.
 ***
 **/
function get_performance_info()
{
    if (!get_config('perftofoot') && !get_config('perftolog')) {
        return array();
    }
    global $PERF;
    $info = array();
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
    if (function_exists('memory_get_usage')) {
        $info['memory_total'] = memory_get_usage();
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
    }
    $inc = get_included_files();
    $info['includecount'] = count($inc);
    $info['dbreads'] = $PERF->dbreads;
    $info['dbwrites'] = $PERF->dbwrites;
    $info['dbcached'] = $PERF->dbcached;
    if (function_exists('posix_times')) {
        $ptimes = posix_times();
        if (is_array($ptimes)) {
            foreach ($ptimes as $key => $val) {
                $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
            }
        }
    }
    // Grab the load average for the last minute
    // /proc will only work under some linux configurations
    // while uptime is there under MacOSX/Darwin and other unices
    if (is_readable('/proc/loadavg') && ($loadavg = @file('/proc/loadavg'))) {
        list($server_load) = explode(' ', $loadavg[0]);
        unset($loadavg);
    } else {
        if (function_exists('is_executable') && is_executable('/usr/bin/uptime') && ($loadavg = `/usr/bin/uptime`)) {
            if (preg_match('/load averages?: (\\d+[\\.,:]\\d+)/', $loadavg, $matches)) {
                $server_load = $matches[1];
            } else {
                log_debug('PERF: Could not parse uptime output!');
            }
        }
    }
    if (!empty($server_load)) {
        $info['serverload'] = $server_load;
    } else {
        $info['serverload'] = 'unknown';
    }
    return $info;
}