Exemple #1
1
 public function __construct($filename)
 {
     $this->fn = $filename;
     $this->fh = @fopen($this->fn, 'w');
     if (!flock($this->fh, LOCK_EX + LOCK_NB)) {
         throw new LockManagerRunningException('Bot already running!');
     } else {
         declare (ticks=10000);
         register_tick_function(array(&$this, 'reLock'), true);
     }
 }
Exemple #2
0
 /**
  * Instantiate a new CliProject object
  *
  * @param null  $request the action request notation
  * @param array $parameters parameters to pass to the action
  *
  * @throws SynergyException
  */
 public function __construct($request = null, array $parameters = array())
 {
     register_tick_function(array(&$this, "checkExit"));
     // Check this is coming from the CLI
     if (PHP_SAPI !== 'cli') {
         throw new SynergyException(sprintf('%s must be run from command line project', __CLASS__));
     }
     // Store or build the request
     $this->parameters = $parameters;
     if (!is_null($request)) {
         $this->request = $request;
     } else {
         $this->args = ArgumentParser::parseArguments();
         $this->request = $this->args->getRequest();
     }
     Logger::debug('CliProject started (pid=' . getmypid() . ')');
     if (is_null($this->args->getRequest())) {
         Logger::emergency('No controller request provided');
         exit(1);
     }
     $this->registerSignalHandler();
     if ($this->args->arg('app')) {
         $this->setAppDir($this->args->arg('app'));
     }
     if ($this->args->arg('conf')) {
         $this->setConfigFilename($this->args->arg('conf'));
     }
     parent::__construct();
 }
Exemple #3
0
 /**
  * Start profiler
  * @param bool $registerTick
  */
 public function start($registerTick = true)
 {
     $this->_startTime = microtime(true);
     $this->_startMemory = memory_get_usage(false);
     if ($registerTick && Sys::isFunc('register_tick_function')) {
         register_tick_function(array($this, 'tick'));
     }
 }
Exemple #4
0
 /**
  * Starts profiler instance.
  * Register profiler handlers.
  */
 public static function start()
 {
     $profiler = self::getInstance();
     register_shutdown_function(array($profiler, 'shutdown'));
     register_tick_function(array($profiler, 'tickHandler'));
     declare (ticks=1);
     // will make first call to tickHandler
 }
Exemple #5
0
 public function run()
 {
     declare (ticks=500);
     register_tick_function([$this->socketStreamer(), 'mainIteration']);
     rabbit::factory($this->config['queue']['section'])->getQueue($this->config['queue']['queueName'])->consume(function ($input) {
         $this->consume($input);
     }, AMQP_AUTOACK);
 }
Exemple #6
0
 /**
  * @return self
  */
 public static function getInstance() : self
 {
     if (self::$instance !== null) {
         return self::$instance;
     }
     self::$instance = new self();
     \register_tick_function(array(self::$instance, 'tick'));
     return self::$instance;
 }
Exemple #7
0
 public function actionTicks()
 {
     declare (ticks=10) {
         register_tick_function('tick_handler');
         for ($i = 0; $i < 10000; $i++) {
             println($i);
         }
     }
 }
 function PerformanceChecker($use_ob)
 {
     $this->now = time() + microtime();
     register_tick_function(array(&$this, 'check'), true);
     register_shutdown_function(array(&$this, "dump"));
     if ($use_ob) {
         ob_start(array(&$this, 'ob'));
     }
 }
Exemple #9
0
 /**
  * 
  * @param callable $function A function to be measured
  * @param array $args Parameters to be passed for measured function
  * @return array Result currently contains one value: used memory space
  */
 public function benchmarkMemory(callable $function, array $args = array())
 {
     declare (ticks=1);
     $this->memory = memory_get_usage();
     $this->max = 0;
     register_tick_function('call_user_func', array($this, 'memoryTick'));
     $this->measureFunction($function, $args, 1);
     unregister_tick_function('call_user_func');
     return array(self::MEMORY_VALUE => $this->max);
 }
Exemple #10
0
 public function start()
 {
     $this->maxMemory = $this->minMemory = $this->iniMemory = $this->logs = null;
     if (!is_null($this->logFile)) {
         $this->logFileHandler = fopen($this->logFile, "w");
     }
     $this->timeUsed = microtime(true);
     register_tick_function(array($this, "tick"));
     declare (ticks=1);
 }
 public function __construct(KernelInterface $kernel)
 {
     parent::__construct($kernel);
     $this->getDefinition()->addOption(new InputOption('--jms-job-id', null, InputOption::VALUE_REQUIRED, 'The ID of the Job.'));
     $kernel->boot();
     if ($kernel->getContainer()->getParameter('jms_job_queue.statistics')) {
         $this->insertStatStmt = $this->getConnection()->prepare("INSERT INTO jms_job_statistics (job_id, characteristic, createdAt, charValue) VALUES (:jobId, :name, :createdAt, :value)");
         register_tick_function(array($this, 'onTick'));
     }
 }
 /**
  * Method used to limit execution time of the script.
  *
  * @access public
  * @param int ($exec_time_ms) - execution time in ms
  * @param bool ($is_bot) - shows the mode in which script was run
  */
 public static function execTimer($exec_time_ms, $is_bot = false, $start = 0)
 {
     $exec_time = $exec_time_ms / 1000;
     declare (ticks=1);
     // or more if 1 takes too much time
     if (empty($start)) {
         $start = microtime(1);
     }
     register_tick_function('tick_timer', $start, $exec_time, $is_bot);
 }
 /**
  * Start
  */
 public static function start()
 {
     // get buffer
     if (ob_get_level()) {
         self::$ob_start = true;
         self::$buffer = @ob_get_clean();
     }
     register_tick_function('alive_tick');
     declare (ticks=200000);
     self::$alive = true;
 }
Exemple #14
0
 private function __construct()
 {
     $self = $this;
     $this->prepareEvent('tick');
     $this->prepareEvent('shutdown');
     \register_tick_function(function () use($self) {
         $self->fireEvent('tick');
     });
     register_shutdown_function(function () use($self) {
         $self->fireEvent('shutdown');
     });
 }
Exemple #15
0
 public static function profile($file = null, $binary = false)
 {
     declare (ticks=1);
     if ($file == null) {
         $file = 'profiler.log';
     }
     self::$binlog = (bool) $binary;
     self::$tracetarget = $file;
     self::$tracestart = microtime(true);
     if (self::$binlog) {
         self::$tracelog = new \Cherry\BinaryLog(self::$tracetarget, "w");
         self::$tracelog->setCompress(true);
     } else {
         self::$tracelog = fopen(self::$tracetarget, "w");
     }
     register_tick_function("Cherry\\Util\\AppProfiler::__appprofiler_ontick");
 }
 /**
  *  Appologies for the commented code.
  *  I would like to restore this functionality eventually.
  *  this is supposed to verify that ticks is a small enough number, as required
  *  by pnctl to fork and manage signals but that static var manipulation doesn't
  *  work from PHP7 so we'll disable for now
  */
 private function setup_ticks()
 {
     $tick_f = function () {
         ForkManager::confirmTicks();
     };
     register_tick_function($tick_f);
     // This is a short NOP+microsleep, just to
     // give verify_declare_ticks() a change to verify.
     $i = 0;
     $i++;
     $i++;
     $i++;
     time_nanosleep(0, 5000);
     if (self::$have_ticks) {
         unregister_tick_function($tick_f);
     } else {
         die("FM requires a 'declare(ticks=1);' in the calling code.\n");
     }
 }
Exemple #17
0
 private function checkForDeclareDirective()
 {
     // PHP7 appears to exhibit different behavior with ticks than
     // 5. Basically, >=7 requires the tick handler at the top of this
     // file for this to execute at all (making the detection
     // pointless), but it doesn't persist in the rest of the script.
     if (version_compare(\PHP_VERSION, '7.0.0', '>=')) {
         return;
     }
     register_tick_function([$this, 'didTick']);
     usleep(1);
     if (!$this->didTick) {
         // Try a bunch of no-ops in case the directive is set as > 1
         $i = 1000;
         while ($i--) {
         }
     }
     unregister_tick_function([$this, 'didTick']);
     if (!$this->didTick) {
         fwrite(STDERR, "It looks like `declare(ticks=1);` has not been " . "called, so signals to stop the daemon will fail. Ensure " . "that the root-level script calls this.\n");
         exit(1);
     }
 }
Exemple #18
0
}
$NETCAT_FOLDER = realpath(dirname(__FILE__) . "/../../../../");
putenv("DOCUMENT_ROOT={$NETCAT_FOLDER}");
putenv("HTTP_HOST=localhost");
putenv("REQUEST_URI=/");
require_once "{$NETCAT_FOLDER}/vars.inc.php";
require_once $ROOT_FOLDER . "connect_io.php";
$nc_core = nc_Core::get_object();
$nc_core->modules->load_env('ru');
$lang = $nc_core->lang->detect_lang();
require_once $ADMIN_FOLDER . "lang/" . $lang . ".php";
error_reporting(E_PARSE | E_ERROR | E_WARNING | E_USER_ERROR | E_USER_WARNING);
// замедление работы при необходимости
$delay = trim(nc_search::get_setting('IndexerConsoleSlowdownDelay'));
// секунды
if ($delay) {
    define('NC_SEARCH_INDEXER_DELAY_VALUE', (int) ($delay * 1000000));
    // микросекунды
    function nc_search_indexer_delay()
    {
        usleep(NC_SEARCH_INDEXER_DELAY_VALUE);
    }
    register_tick_function('nc_search_indexer_delay');
    declare (ticks=10000);
}
while (@ob_end_flush()) {
}
// Поменяйте nc_search::LOG_CONSOLE на другое значение, если хотите получать
// больше или меньше информации о переиндексации
nc_search::register_logger(new nc_search_logger_plaintext(nc_search::LOG_CONSOLE));
nc_search_scheduler::run(nc_search::INDEXING_CONSOLE);
 /**
  * Set a time limit (in seconds) for the current script. After time expires,
  * the script fatals.
  *
  * This works like `max_execution_time`, but prints out a useful stack trace
  * when the time limit expires. This is primarily intended to make it easier
  * to debug pages which hang by allowing extraction of a stack trace: set a
  * short debug limit, then use the trace to figure out what's happening.
  *
  * The limit is implemented with a tick function, so enabling it implies
  * some accounting overhead.
  *
  * @param int Time limit in seconds.
  * @return void
  */
 public static function setDebugTimeLimit($limit)
 {
     self::$debugTimeLimit = $limit;
     static $initialized;
     if (!$initialized) {
         declare (ticks=1);
         register_tick_function(array(__CLASS__, 'onDebugTick'));
     }
 }
Exemple #20
0
 function runTests($test_obj = null)
 {
     if (!$test_obj) {
         $test_obj = $this;
     }
     $tested = array();
     $data = array();
     foreach (get_class_methods($test_obj) as $method) {
         $m = '';
         if (strpos($method, 'test_') === 0) {
             $m = substr($method, 5);
         } elseif (strpos($method, 'prepare_') === 0) {
             $m = substr($method, 8);
         } else {
             continue;
         }
         if (isset($_GET['testonly']) && 'test_' . $_GET['testonly'] != $method) {
             continue;
         }
         // Do not retest same function even if it has both prepare and test
         if ($tested[$m]) {
             continue;
         }
         $tested[$m] = true;
         // Row contains test result data
         $row = array('name' => $m, 'id' => $m);
         foreach ($this->variances as $key => $vari) {
             if (is_numeric($key)) {
                 $key = $vari;
             }
             try {
                 // Input is a result of preparation function
                 if (method_exists($test_obj, 'prepare_' . $m)) {
                     $input = $test_obj->{'prepare_' . $m}($vari, $method);
                 } else {
                     if ($test_obj->hasMethod('prepare')) {
                         $input = $test_obj->prepare($vari, $method);
                     } else {
                         $input = null;
                     }
                 }
             } catch (Exception $e) {
                 if ($e instanceof Exception_SkipTests) {
                     $this->grid->destroy();
                     $this->add('View_Error')->set('Skipping all tests: ' . $e->getMessage());
                     return;
                 }
             }
             $this->input = $input;
             $test_func = method_exists($test_obj, 'test_' . $m) ? 'test_' . $m : 'test';
             // Test speed
             $me = memory_get_peak_usage();
             $ms = microtime(true);
             $this->cnt = 0;
             declare (ticks=1);
             register_tick_function(array($this, 'ticker'));
             try {
                 //$result=$test_obj->$test_func($input[0],$input[1],$input[2]);
                 $result = $this->executeTest($test_obj, $test_func, $input);
             } catch (Exception $e) {
                 if ($e instanceof Exception_SkipTests) {
                     $this->grid->destroy();
                     $this->add('View_Error')->set('Skipping all tests: ' . $e->getMessage());
                 }
                 if ($_GET['tester_details'] == $row['name'] && $_GET['vari'] == $vari) {
                     throw $e;
                 }
                 $result = 'Exception: ' . (method_exists($e, 'getText') ? $e->getText() : $e->getMessage());
                 $ll = $this->add('P', $row['name']);
                 $v = $ll->add('View')->setElement('a')->setAttr('href', '#')->set('More details')->js('click')->univ()->frameURL('Exception Details for test ' . $row['name'], $this->api->url(null, array('tester_details' => $row['name'], 'vari' => $vari)));
                 $result .= $ll->getHTML();
             }
             $ms = microtime(true) - $ms;
             $me = ($mend = memory_get_peak_usage()) - $me;
             unregister_tick_function(array($this, 'ticker'));
             $row[$key . '_inf'] = 'Ticks: ' . $this->cnt * 1 . '<br/>Memory: ' . $me;
             $result = $this->formatResult($row, $key, $result);
             $k = $key . '_' . $row['name'];
             if ($this->proper_responses[$k] == $result && isset($this->proper_responses[$k])) {
                 $row[$key . '_res'] = '<font color="green">PASS</font><br/>' . htmlspecialchars($result);
             } elseif ($this->proper_responses[$k]) {
                 $row[$key . '_res'] = '<font color="red">' . htmlspecialchars($result) . '</font><br/>' . var_export($this->proper_responses[$k], true);
             }
             $this->responses[] = '"' . $k . '"' . '=>' . var_export($result, true);
         }
         $data[] = $row;
     }
     $this->grid->setSource($data);
 }
 /**
  * Constructor
  * Initialize the object, figure out if profiling is enabled, and if so,
  * start the profile.
  * @return p3_profiler
  */
 public function __construct()
 {
     // Set up paths
     $this->_P3_PATH = realpath(dirname(__FILE__));
     // Debug mode
     $this->_debug_entry = array('profiling_enabled' => false, 'recording_ip' => '', 'scan_name' => '', 'recording' => false, 'disable_optimizers' => false, 'url' => $this->_get_url(), 'visitor_ip' => p3_profiler_get_ip(), 'time' => time(), 'pid' => getmypid());
     // Check to see if we should profile
     $opts = array();
     if (function_exists('get_option')) {
         $opts = get_option('p3-profiler_options');
         if (!empty($opts['profiling_enabled'])) {
             if (isset($this->_debug_entry)) {
                 $this->_debug_entry['profiling_enabled'] = true;
                 $this->_debug_entry['scan_name'] = $opts['profiling_enabled']['name'];
                 $this->_debug_entry['recording_ip'] = $opts['profiling_enabled']['ip'];
                 $this->_debug_entry['disable_optimizers'] = $opts['profiling_enabled']['disable_opcode_cache'];
             }
         }
     }
     // Add a global flag to let everyone know we're profiling
     if (!empty($opts) && preg_match('/' . $opts['profiling_enabled']['ip'] . '/', p3_profiler_get_ip())) {
         define('WPP_PROFILING_STARTED', true);
     }
     // Save the debug info
     $this->_debug_entry['recording'] = defined('WPP_PROFILING_STARTED');
     // Check the profiling flag
     if (!defined('WPP_PROFILING_STARTED')) {
         return $this;
     }
     // Emergency shut off switch
     if (isset($_REQUEST['P3_SHUTOFF']) && !empty($_REQUEST['P3_SHUTOFF'])) {
         p3_profiler_disable();
         return $this;
     }
     // Hook shutdown
     register_shutdown_function(array($this, 'shutdown_handler'));
     // Error detection
     $flag = get_option('p3_profiler-error_detection');
     if (!empty($flag) && $flag > time() + 60) {
         p3_profiler_disable();
         return $this;
     }
     // Set the error detection flag
     if (empty($flag)) {
         update_option('p3_profiler-error_detection', time());
     }
     // Kludge memory limit / time limit
     if ((int) @ini_get('memory_limit') < 256) {
         @ini_set('memory_limit', '256M');
     }
     @set_time_limit(90);
     // Set the profile file
     $this->_profile_filename = $opts['profiling_enabled']['name'] . '.json';
     // Start timing
     $this->_start_time = microtime(true);
     $this->_last_call_start = microtime(true);
     // Reset state
     $this->_last_call_time = 0;
     $this->_runtime = 0;
     $this->_plugin_runtime = 0;
     $this->_core = 0;
     $this->_theme = 0;
     $this->_last_call_category = self::CATEGORY_CORE;
     $this->_last_stack = array();
     // Add some startup information
     $this->_profile = array('url' => $this->_get_url(), 'ip' => p3_profiler_get_ip(), 'pid' => getmypid(), 'date' => @date('c'), 'stack' => array());
     // Disable opcode optimizers.  These "optimize" calls out of the stack
     // and hide calls from the tick handler and backtraces
     if ($opts['profiling_enabled']['disable_opcode_cache']) {
         if (extension_loaded('xcache')) {
             @ini_set('xcache.optimizer', false);
             // Will be implemented in 2.0, here for future proofing
             // XCache seems to do some optimizing, anyway.  The recorded stack size is smaller with xcache.cacher enabled than without.
         } elseif (extension_loaded('apc')) {
             @ini_set('apc.optimization', 0);
             // Removed in APC 3.0.13 (2007-02-24)
             apc_clear_cache();
         } elseif (extension_loaded('eaccelerator')) {
             @ini_set('eaccelerator.optimizer', 0);
             if (function_exists('eaccelerator_optimizer')) {
                 @eaccelerator_optimizer(false);
             }
             // If you're reading this, try setting eaccelerator.optimizer = 0 in a .user.ini or .htaccess file
         } elseif (extension_loaded('Zend Optimizer+')) {
             @ini_set('zend_optimizerplus.optimization_level', 0);
         }
         // Tested with wincache
         // Tested with ioncube
         // Tested with zend guard loader
     }
     // Monitor all function-calls
     declare (ticks=1);
     register_tick_function(array($this, 'tick_handler'));
 }
Exemple #22
0
{
    static $times;
    $len = [];
    switch ($display) {
        case false:
            $times[] = microtime(true);
            break;
        case true:
            $start_total = array_shift($times);
            foreach ($times as $stop) {
                $stop_total = $stop;
                $len[] = $stop_total - $start_total;
            }
            unset($times);
            return $len;
            break;
    }
}
register_tick_function('profile');
declare (ticks=1) {
    foreach ($_SERVER['argv'] as $arg) {
        "{$arg}:" . strlen($arg) . "\n";
    }
}
// (profile ( true ) );
print "---\n";
$i = 0;
foreach (profile(true) as $time) {
    $i++;
    print "Line {$i}:{$time}\n";
}
echo DUDE . PHP_EOL;
echo Dude . PHP_EOL;
// PHP Notice: undefined constant Dude
const DUDES = 20;
echo DUDES . PHP_EOL;
//const NAMES = ["foo", "bar"];
//const COMPOSIBLE = "COMPOSIBLE". NAMES[0];
//echo COMPOSIBLE . PHP_EOL;
echo __FILE__ . PHP_EOL;
echo __DIR__ . PHP_EOL;
echo __LINE__ . PHP_EOL;
// condition scope
$test = 10;
if ($test == 10) {
    $test_d = 20;
    // variable hoisting
}
echo $test_d . PHP_EOL;
// ticks
declare (ticks=1) {
    // same for encoding=utf-8 and strict_types
    function tick_handler()
    {
        echo "tick_handler() called" . PHP_EOL;
    }
    register_tick_function(tick_handler);
    if (true) {
        $a = 10;
    }
    $b = 20;
}
Exemple #24
0
 /**
  * Set the callback fucntion to process the watches, enabled depending of 
  * the options flag 'enable_watch' 
  * 
  * @since V2.0.0 - 16 apr 2006
  * @see options, watches, watchesCallback()
  */
 protected function setWatchCallback()
 {
     if ($this->options['enable_watch'] == true) {
         if (count($this->watches) === 0) {
             $watchMethod = array($this, 'watchesCallback');
             register_tick_function($watchMethod);
         }
     }
 }
Exemple #25
0
 /**
  * @brief Constructor.
  */
 public function __construct()
 {
     Console::debug("Constructing service instance");
     // register_shutdown_function(array(&$this, 'fatal'));
     gc_enable();
     declare (ticks=1);
     register_tick_function(array($this, 'checkstate'));
     parent::__construct();
 }
<?php

register_tick_function('profile');
register_tick_function('backup');
declare (ticks=3) {
    // code...
}
Exemple #27
0
<?php

function a()
{
    echo "hello";
    unregister_tick_function('a');
}
declare (ticks=1);
register_tick_function('a');
echo "Done\n";
Exemple #28
0
        print "debug " . $file . "> initialize\n";
        $start_time = time() + microtime();
        $start_code_line = $code_line;
        return 0;
    }
    printf("debug %s> code-lines: %d-%d time: %.4f mem: %d KB\n", $file, $start_code_line, $code_line, time() + microtime() - $start_time, ceil(memory_get_usage() / 1024));
    $start_time = time() + microtime();
    $start_code_line = $code_line;
}
function time_debug()
{
    static $start_time = 0;
    static $end_time = 0;
    $start_time = $end_time;
    $end_time = microtime(1);
    $debug = debug_backtrace();
    echo $debug[1]['line'], "\t", $start_time > 0 ? $end_time - $start_time : 0, "s\n";
}
function doTicks()
{
    time_debug();
}
register_tick_function('doTicks');
declare (ticks=1);
$i = 2;
while ($i) {
    echo "bbb", "\n";
    sleep(2);
    echo 'aaa', "\n";
    $i--;
}
 /**
  * Constructor
  */
 public function __construct()
 {
     $this->inotifyStreamDescriptor = inotify_init();
     stream_set_blocking($this->inotifyStreamDescriptor, 0);
     register_tick_function([$this, 'tick']);
 }
                call_user_func_array($load_callback, array($parameters));
            } else {
                do_action('fw_cache_load', $parameters);
            }
            unset($parameters);
            // try again to get value (maybe someone loaded it)
            $value = fw_akg($keys, self::$cache, self::$not_found_value, $keys_delimiter);
            if ($value === self::$not_found_value) {
                throw new FW_Cache_Not_Found_Exception('Cache key not found: ' . $keys);
            }
        }
        return $value;
    }
    /**
     * Empty the cache
     */
    public static function clear()
    {
        self::$cache = array();
    }
}
FW_Cache::_init();
class FW_Cache_Not_Found_Exception extends Exception
{
}
/**
 * 3000: ~15 times
 */
declare (ticks=3000);
register_tick_function(array('FW_Cache', 'free_memory'));