/** * Compute an estimate of available memory from memory limit and memory usage. * The memory limit value is extracted from php.ini configuration directive memory_limit, and converted to bytes. */ public static function memory_get_available() { static $limit = null; if (!isset($limit)) { $inilimit = trim(ini_get('memory_limit')); if (empty($inilimit)) { // no limit set $limit = false; } elseif (ctype_digit($inilimit)) { $limit = (int) $inilimit; } else { $limit = (int) substr($inilimit, 0, -1); switch (strtolower(substr($inilimit, -1))) { case 'g': $limit *= 1024; case 'm': $limit *= 1024; case 'k': $limit *= 1024; } } } if ($limit !== false) { return $limit - memory_get_usage(true); } else { return false; } }
public function stop() { $time = round(microtime(true) - $this->time_point, 5); $memory = round(memory_get_usage() - $this->memory_point, 5); $memory = $this->memory_format($memory); return array('time' => $time, 'memory' => $memory); }
public function execute(CommandSender $sender, $currentAlias, array $args) { if (!$this->testPermission($sender)) { return true; } $chunksCollected = 0; $entitiesCollected = 0; $tilesCollected = 0; $memory = memory_get_usage(); foreach ($sender->getServer()->getLevels() as $level) { $diff = [count($level->getChunks()), count($level->getEntities()), count($level->getTiles())]; $level->doChunkGarbageCollection(); $level->unloadChunks(true); $chunksCollected += $diff[0] - count($level->getChunks()); $entitiesCollected += $diff[1] - count($level->getEntities()); $tilesCollected += $diff[2] - count($level->getTiles()); $level->clearCache(true); } $cyclesCollected = $sender->getServer()->getMemoryManager()->triggerGarbageCollector(); $sender->sendMessage(TextFormat::GREEN . "---- " . TextFormat::WHITE . "Garbage collection result" . TextFormat::GREEN . " ----"); $sender->sendMessage(TextFormat::GOLD . "Chunks: " . TextFormat::RED . number_format($chunksCollected)); $sender->sendMessage(TextFormat::GOLD . "Entities: " . TextFormat::RED . number_format($entitiesCollected)); $sender->sendMessage(TextFormat::GOLD . "Tiles: " . TextFormat::RED . number_format($tilesCollected)); $sender->sendMessage(TextFormat::GOLD . "Cycles: " . TextFormat::RED . number_format($cyclesCollected)); $sender->sendMessage(TextFormat::GOLD . "Memory freed: " . TextFormat::RED . number_format(round(($memory - memory_get_usage()) / 1024 / 1024, 2)) . " MB"); return true; }
/** * 显示运行时间、数据库操作、缓存次数、内存使用信息 * @access private * @return string */ private function showTime() { // 显示运行时间 G('beginTime', $GLOBALS['_beginTime']); G('viewEndTime'); $showTime = 'Process: ' . G('beginTime', 'viewEndTime') . 's '; if (C('SHOW_ADV_TIME')) { // 显示详细运行时间 $showTime .= '( Load:' . G('beginTime', 'loadTime') . 's Init:' . G('loadTime', 'initTime') . 's Exec:' . G('initTime', 'viewStartTime') . 's Template:' . G('viewStartTime', 'viewEndTime') . 's )'; } if (C('SHOW_DB_TIMES') && class_exists('Db', false)) { // 显示数据库操作次数 $showTime .= ' | DB :' . N('db_query') . ' queries ' . N('db_write') . ' writes '; } if (C('SHOW_CACHE_TIMES') && class_exists('Cache', false)) { // 显示缓存读写次数 $showTime .= ' | Cache :' . N('cache_read') . ' gets ' . N('cache_write') . ' writes '; } if (MEMORY_LIMIT_ON && C('SHOW_USE_MEM')) { // 显示内存开销 $showTime .= ' | UseMem:' . number_format((memory_get_usage() - $GLOBALS['_startUseMems']) / 1024) . ' kb'; } if (C('SHOW_LOAD_FILE')) { $showTime .= ' | LoadFile:' . count(get_included_files()); } if (C('SHOW_FUN_TIMES')) { $fun = get_defined_functions(); $showTime .= ' | CallFun:' . count($fun['user']) . ',' . count($fun['internal']); } return $showTime; }
/** * 获得查询次数以及查询时间 * * @access public * @return string */ function insert_query_info() { if ($GLOBALS['db']->queryTime == '') { $query_time = 0; } else { if (PHP_VERSION >= '5.0.0') { $query_time = number_format(microtime(true) - $GLOBALS['db']->queryTime, 6); } else { list($now_usec, $now_sec) = explode(' ', microtime()); list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime); $query_time = number_format($now_sec - $start_sec + ($now_usec - $start_usec), 6); } } /* 内存占用情况 */ if ($GLOBALS['_LANG']['memory_info'] && function_exists('memory_get_usage')) { $memory_usage = sprintf($GLOBALS['_LANG']['memory_info'], memory_get_usage() / 1048576); } else { $memory_usage = ''; } /* 是否启用了 gzip */ $gzip_enabled = gzip_enabled() ? $GLOBALS['_LANG']['gzip_enabled'] : $GLOBALS['_LANG']['gzip_disabled']; $online_count = $GLOBALS['db']->getOne("SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('sessions')); /* 加入触发cron代码 */ $cron_method = empty($GLOBALS['_CFG']['cron_method']) ? '<img src="api/cron.php?t=' . gmtime() . '" alt="" style="width:0px;height:0px;" />' : ''; return sprintf($GLOBALS['_LANG']['query_info'], $GLOBALS['db']->queryCount, $query_time, $online_count) . $gzip_enabled . $memory_usage . $cron_method; }
/** * Retrieve loaded category collection * * @return Mage_Eav_Model_Entity_Collection_Abstract */ public function getLoadedProductCollectionpro($id) { // benchmarking $memory = memory_get_usage(); $time = microtime(); if (is_null($this->_productCollection)) { $layer = $this->getLayer(); if ($this->getShowRootCategory()) { $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId()); } // if this is a product view page if (Mage::registry('product')) { // get collection of categories this product is associated with $categories = Mage::registry('product')->getCategoryCollection()->setPage(1, 1)->load(); // if the product is associated with any category if ($categories->count()) { // show products from this category $this->setCategoryId(current($categories->getIterator())); } } $origCategory = null; if ($this->getCategoryId()) { $category = Mage::getModel('catalog/category')->load($this->getCategoryId()); if ($category->getId()) { $origCategory = $layer->getCurrentCategory(); $layer->setCurrentCategory($category); $this->addModelTags($category); } } /* @var $layer Mage_Catalog_Model_Layer */ /* @var $layer Mage_Catalog_Model_Layer */ //$this->_productCollection = $layer->getProductCollection(); /** @var $collection Mage_Catalog_Model_Resource_Product_Collection */ $category = Mage::getModel('catalog/category')->load($this->_theCat); $this->_productCollection = Mage::getResourceModel('catalog/product_collection'); // join sales order items column and count sold products $expression = new Zend_Db_Expr("SUM(oi.qty_ordered)"); $condition = new Zend_Db_Expr("e.entity_id = oi.product_id AND oi.parent_item_id IS NULL"); $this->_productCollection->addAttributeToSelect('*')->getSelect()->join(array('oi' => $this->_productCollection->getTable('sales/order_item')), $condition, array('sales_count' => $expression))->group('e.entity_id'); //->order('sales_count' . ' ' . 'desc'); $this->_productCollection->addFieldToFilter('status', '1'); //join brand if ($this->getRequest()->getParam('brands_ids') != null and $this->getRequest()->getParam('brands_ids') != 0) { $brand_id = $this->getRequest()->getParam('brands_ids'); $condition = new Zend_Db_Expr("br.option_id = {$brand_id} AND br.product_ids = e.entity_id"); $this->_productCollection->getSelect()->join(array('br' => $this->_productCollection->getTable('shopbybrand/brand')), $condition, array('brand_id' => 'br.option_id')); } // join category $condition = new Zend_Db_Expr("e.entity_id = ccp.product_id"); $condition2 = new Zend_Db_Expr("c.entity_id = ccp.category_id"); $this->_productCollection->getSelect()->join(array('ccp' => $this->_productCollection->getTable('catalog/category_product')), $condition, array())->join(array('c' => $this->_productCollection->getTable('catalog/category')), $condition2, array('cat_id' => 'c.entity_id')); $condition = new Zend_Db_Expr("c.entity_id = cv.entity_id AND ea.attribute_id = cv.attribute_id"); // cutting corners here by hardcoding 3 as Category Entiry_type_id $condition2 = new Zend_Db_Expr("ea.entity_type_id = 3 AND ea.attribute_code = 'name'"); $this->_productCollection->getSelect()->join(array('ea' => $this->_productCollection->getTable('eav/attribute')), $condition2, array())->join(array('cv' => $this->_productCollection->getTable('catalog/category') . '_varchar'), $condition, array('cat_name' => 'cv.value')); $id = $this->getRequest()->getParam('id'); $this->_productCollection->getSelect()->where('c.entity_id = ?', $id)->limit(20); } return $this->_productCollection; }
public static function memory_usage() { $bytes = memory_get_usage(); $kbytes = $bytes / 1024; $mbytes = $kbytes / 1024; return round($mbytes, 3); }
/** +---------------------------------------------------------- * 显示运行时间、数据库操作、缓存次数、内存使用信息 +---------------------------------------------------------- * @access private +---------------------------------------------------------- * @return string +---------------------------------------------------------- */ private function showTime() { // 显示运行时间 G('beginTime', $GLOBALS['_beginTime']); G('viewEndTime'); $showTime = 'Process: ' . G('beginTime', 'viewEndTime') . 's '; // 显示详细运行时间 $showTime .= '( Load:' . G('beginTime', 'loadTime') . 's Init:' . G('loadTime', 'initTime') . 's Exec:' . G('initTime', 'viewStartTime') . 's Template:' . G('viewStartTime', 'viewEndTime') . 's )'; // 显示数据库操作次数 if (class_exists('Db', false)) { $showTime .= ' | DB :' . N('db_query') . ' queries ' . N('db_write') . ' writes '; } // 显示缓存读写次数 if (class_exists('Cache', false)) { $showTime .= ' | Cache :' . N('cache_read') . ' gets ' . N('cache_write') . ' writes '; } // 显示内存开销 if (MEMORY_LIMIT_ON) { $showTime .= ' | UseMem:' . number_format((memory_get_usage() - $GLOBALS['_startUseMems']) / 1024) . ' kb'; } // 显示文件加载数 $showTime .= ' | LoadFile:' . count(get_included_files()); // 显示函数调用次数 自定义函数,内置函数 $fun = get_defined_functions(); $showTime .= ' | CallFun:' . count($fun['user']) . ',' . count($fun['internal']); return $showTime; }
function on_complete($req) { echo "request complete: " . evhttp_request_status($req) . "\n"; //echo evhttp_request_body($req)."\n"; evhttp_request_free($req); echo memory_get_usage() . "\n\n"; }
protected function execute($arguments = array(), $options = array()) { if (!$this->safeToRun()) { print "Process already running!\n"; die; } $timer = sfTimerManager::getTimer('execute'); $databaseManager = new sfDatabaseManager($this->configuration); $databaseManager->initialize($this->configuration); //set up index $index = EntityTable::getLuceneIndex(); //delete deleted entities $q = LsDoctrineQuery::create()->from('Entity e')->where('e.is_deleted = ?', true)->setHydrationMode(Doctrine::HYDRATE_ARRAY); foreach ($q->execute() as $entity) { if ($hits = $index->find('key:' . $entity['id'])) { if ($options['debug_mode']) { printf("Deleting index for Entity %s\n", $entity['id']); } foreach ($hits as $hit) { $index->delete($hit->id); } } } printf("Memory used: %s\n", LsNumber::makeBytesReadable(memory_get_usage())); printf("Index size: %s\n", $index->count()); $timer->addTime(); printf("Run time: %s\n", $timer->getElapsedTime()); sfTimerManager::clearTimers(); }
protected function init() { try { $this->data['timestamp'] = time(); $this->data['direction'] = waRequest::post('direction', 'import'); $type_model = new shopTypeModel(); $this->data['types'] = array_map('intval', array_keys($type_model->getTypes())); switch ($this->data['direction']) { case 'export': $this->initExport(); break; case 'import': default: $this->data['direction'] = 'import'; $this->initImport(); break; } $stages = array_keys($this->data['count']); $this->data['current'] = array_fill_keys($stages, 0); $value = $this->data['direction'] == 'import' ? $this->emulate(null) ? array('add' => 0, 'found' => 0, 'skip' => 0, 'rights' => 0, 'currency' => 0) : array('new' => 0, 'update' => 0, 'skip' => 0, 'error' => 0, 'rights' => 0, 'currency' => 0) : 0; $this->data['processed_count'] = array_fill_keys($stages, $value); $this->data['map'] = array(); $this->data['memory'] = memory_get_peak_usage(); $this->data['memory_avg'] = memory_get_usage(); $this->data['timestamp'] = time(); } catch (waException $ex) { $this->error($ex->getMessage()); echo $this->json(array('error' => $ex->getMessage())); exit; } }
/** * Returns the current memory usage in MB * @param int $precision 1-8 (default 4) * @return float */ public static function getMemoryUsage($precision = 4) { if (!is_int($precision) || $precision < 1 || $precision > 8) { $precision = 4; } return number_format(memory_get_usage() / 1024 / 1024, $precision); }
/** * * @param nc_search_indexer $indexer * @param $cycle_number * @return boolean TRUE: остановка для перезапуска, FALSE: продолжение выполнения */ protected function interrupt_if_needed(nc_search_indexer $indexer, $cycle_number) { $memory_use = function_exists('memory_get_usage') ? memory_get_usage() : 0; $time_use = time() + $this->delay - $this->start_time; $out_of_memory = $out_of_time = false; // проверяем память if ($this->memory_threshold > 0) { if ($this->memory_threshold <= 1) { // относительные значения $out_of_memory = $memory_use / $this->memory_limit >= $this->memory_threshold; } else { // абсолютные значения $out_of_memory = $memory_use >= $this->memory_threshold; } } // проверяем время if ($this->time_threshold > 0) { if ($this->time_threshold <= 1) { // относительные значения // 'max_execution_time' ($this->time_limit) может быть равен 0 при запуске из консоли $out_of_time = $this->time_limit && $time_use / $this->time_limit >= $this->time_threshold; } else { // абсолютные значения $out_of_time = $time_use >= $this->time_threshold; } } // проверяем ограничение на количество циклов $is_last_cycle = $this->cycle_limit > 0 && $cycle_number > $this->cycle_limit; // останавливаемся, когда достигли лимита if ($out_of_memory || $out_of_time || $is_last_cycle) { $indexer->interrupt("mem: {$memory_use} bytes; time: {$time_use} s"); return true; } return false; }
public function detalleAction($nid, $position = 1) { $start_memory = memory_get_usage(); /*$nota = new \Rpp\Pages\Nota($nid,$this->dispatcher); $di = new Phalcon\DI(); $nota->package ='nota'; $nota->set_position($position); $di->setShared('model',$nota); $di->setShared('viewCache',$this->viewCache); $this->view->setDI($di); $Analytics = new \Rpp\Services\Analytics\Visits\Load\Nota($nid); $Analytics->calculate();*/ if (!Rpp\Pages\Nota::validate($nid)) { $this->dispatcher->forward(array('controller' => 'error', 'action' => 'show404')); } $nota = function () use($nid) { return new \Rpp\Pages\Nota($nid); }; $di = new Phalcon\DI(); $di->set('model', $nota); $di->set('viewCache', $this->viewCache); $this->view->setDI($di); $Analytics = new \Rpp\Services\Analytics\Visits\Load\Nota($nid); $Analytics->calculate(); //var_dump( memory_get_usage() - $start_memory );die(); }
/** * 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; } } }
public function transform() { // get transformed document $doc = $this->__Document->transform(); // set content of body $this->__Layout->__Body()->write($doc); // Verbrauchter PHP Speicher (RAM) $memory = fbytes(memory_get_usage()); // Skriptlaufzeit $runtime = round(microtime(true) - RUNTIME, 5); $req = Singleton::getInstance('HTTP_Request'); if (substr_count($req->getRequestUri(), 'ajax.') > 0) { return $this->__Layout->getAJAX(); } $this->__Layout->__Body()->write('<!-- runtime: ' . $runtime . ' // memory usage: ' . $memory . ' -->'); // check logfiles $sys_logs = scandir(LOG_PATH); if (count($sys_logs) > 2) { jgrowl(count($sys_logs) - 2 . ' Log(s) verfügbar', 'Systemfehler', 'warning'); } $app_logs = scandir(RESOURCE_PATH . '/logs'); if (count($app_logs) > 2) { jgrowl(count($app_logs) - 2 . ' Log(s) verfügbar', 'Anwendungsfehler', 'warning'); } $notes = Singleton::getInstance('Watchdog')->getNotifications(); $this->__Layout->__Body()->write($notes); return $this->__Layout->getLayout(); // end function }
/** * format memory usage * * @return string */ public function formatMemoryUsage() { $sLog = ''; if (function_exists('memory_get_usage')) { $iKb = (int) (memory_get_usage() / 1024); $iMb = round($iKb / 1024, 3); $sLog .= 'Memory usage: ' . $iMb . ' MB'; if (function_exists('memory_get_peak_usage')) { $iPeakKb = (int) (memory_get_peak_usage() / 1024); $iPeakMb = round($iPeakKb / 1024, 3); $sLog .= ' (peak: ' . $iPeakMb . ' MB)'; } $sLog .= '<br />'; if (version_compare(PHP_VERSION, '5.2.0', '>=')) { $iKb = (int) (memory_get_usage(true) / 1024); $iMb = round($iKb / 1024, 3); $sLog .= 'System memory usage: ' . $iMb . ' MB'; if (function_exists('memory_get_peak_usage')) { $iPeakKb = (int) (memory_get_peak_usage(true) / 1024); $iPeakMb = round($iPeakKb / 1024, 3); $sLog .= ' (peak: ' . $iPeakMb . ' MB)'; } $sLog .= '<br />'; } } return $sLog; }
/** * estrae gli N atti più rilevanti per determinati argomenti (tag) */ function run_a0_get_main_acts_for_tags($task, $args, $options) { static $loaded; // load application context if (!$loaded) { task_loader(); $loaded = true; } echo "memory usage: " . memory_get_usage() . "\n"; $msg = sprintf("start time: %s\n", date('H:i:s')); echo $msg; $n = 1; if (array_key_exists('nrecs', $options)) { $n = (int) $options['nrecs']; } if (!is_int($n) || $n < 1) { throw new Exception("il numero di atti deve essere un intero\n"); } if (count($args) > 0) { $argomenti = array(); foreach ($args as $cnt => $arg) { $id = TagPeer::getIdFromTagValue($arg); $xml_url = sprintf("http://parlamento.openpolis.it/xml/indici/tag/%d.xml", $id); $xsl_file = SF_ROOT_DIR . "/web/xml/indici/xslt/tagActsSorter.xslt"; printf("Argomento %s:\n", $arg, $id); getImportantActs($xml_url, $xsl_file, $n); print "\n"; } } $start_time = time(); $msg = sprintf("end time: %s\n", date('H:i:s')); echo $msg; $msg = sprintf("memory usage: %10d\n", memory_get_usage()); echo pakeColor::colorize($msg, array('fg' => 'red', 'bold' => false)); }
public function __invoke(array $record) : array { $bytes = memory_get_usage($this->realUsage); $formatted = $this->formatBytes($bytes); $record['extra']['memory_usage'] = $formatted; return $record; }
/** * Returns current memory usage, if available * * @return int */ private function getMemoryUsage() { if (function_exists('memory_get_usage')) { return memory_get_usage(); } return 0; }
protected function _toHtml() { if (!$this->_beforeToHtml() || !Mage::getStoreConfig('dev/debug/profiler') || !Mage::helper('core')->isDevAllowed()) { return ''; } $timers = Varien_Profiler::getTimers(); #$out = '<div style="position:fixed;bottom:5px;right:5px;opacity:.1;background:white" onmouseover="this.style.opacity=1" onmouseout="this.style.opacity=.1">'; #$out = '<div style="opacity:.1" onmouseover="this.style.opacity=1" onmouseout="this.style.opacity=.1">'; $out = "<a href=\"javascript:void(0)\" onclick=\"\$('profiler_section').style.display=\$('profiler_section').style.display==''?'none':''\">[profiler]</a>"; $out .= '<div id="profiler_section" style="background:white; display:block">'; $out .= '<pre>Memory usage: real: ' . memory_get_usage(true) . ', emalloc: ' . memory_get_usage() . '</pre>'; $out .= '<table border="1" cellspacing="0" cellpadding="2" style="width:auto">'; $out .= '<tr><th>Code Profiler</th><th>Time</th><th>Cnt</th><th>Emalloc</th><th>RealMem</th></tr>'; foreach ($timers as $name => $timer) { $sum = Varien_Profiler::fetch($name, 'sum'); $count = Varien_Profiler::fetch($name, 'count'); $realmem = Varien_Profiler::fetch($name, 'realmem'); $emalloc = Varien_Profiler::fetch($name, 'emalloc'); if ($sum < 0.001 && $count < 10 && $emalloc < 10000) { continue; } $out .= '<tr>' . '<td align="left">' . $name . '</td>' . '<td>' . number_format($sum, 4) . '</td>' . '<td align="right">' . $count . '</td>' . '<td align="right">' . number_format($emalloc) . '</td>' . '<td align="right">' . number_format($realmem) . '</td>' . '</tr>'; } $out .= '</table>'; $out .= '<pre>'; $out .= print_r(Varien_Profiler::getSqlProfiler(Mage::getSingleton('core/resource')->getConnection('core_write')), 1); $out .= '</pre>'; $out .= '</div>'; return $out; }
public function debugHelper() { echo "<pre>"; echo "<b>Kajona V4 Debug Subsystem</b>\n\n"; if (getGet("debugfile") != "") { echo "Loading path for " . getGet("debugfile") . "\n"; $strPath = array_search(getGet("debugfile"), class_resourceloader::getInstance()->getFolderContent("/debug", array(".php"))); if ($strPath !== false) { echo "Passing request to " . $strPath . "\n\n"; include _realpath_ . $strPath; } } else { echo "Searching for debug-scripts available...\n"; $arrFiles = class_resourceloader::getInstance()->getFolderContent("/debug", array(".php")); echo "<ul>"; foreach ($arrFiles as $strPath => $strOneFile) { echo "<li><a href='?debugfile=" . $strOneFile . "' >" . $strOneFile . "</a> <br />" . $strPath . "</li>"; } echo "</ul>"; } $arrTimestampEnde = gettimeofday(); $intTimeUsed = ($arrTimestampEnde['sec'] * 1000000 + $arrTimestampEnde['usec'] - ($this->arrTimestampStart['sec'] * 1000000 + $this->arrTimestampStart['usec'])) / 1000000; echo "\n\n<b>PHP-Time:</b> " . number_format($intTimeUsed, 6) . " sec \n"; echo "<b>Queries db/cachesize/cached/fired:</b> " . class_carrier::getInstance()->getObjDB()->getNumber() . "/" . class_carrier::getInstance()->getObjDB()->getCacheSize() . "/" . class_carrier::getInstance()->getObjDB()->getNumberCache() . "/" . (class_carrier::getInstance()->getObjDB()->getNumber() - class_carrier::getInstance()->getObjDB()->getNumberCache()) . "\n"; echo "<b>Templates cached:</b> " . class_carrier::getInstance()->getObjTemplate()->getNumberCacheSize() . " \n"; echo "<b>Memory/Max Memory:</b> " . bytesToString(memory_get_usage()) . "/" . bytesToString(memory_get_peak_usage()) . " \n"; echo "<b>Classes Loaded:</b> " . class_classloader::getInstance()->getIntNumberOfClassesLoaded() . " \n"; echo "<b>Cache requests/hits/saves/cachesize:</b> " . class_cache::getIntRequests() . "/" . class_cache::getIntHits() . "/" . class_cache::getIntSaves() . "/" . class_cache::getIntCachesize() . " \n"; echo "</pre>"; }
protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; declare (ticks=1); register_shutdown_function(array($this, 'stopCommand')); set_error_handler(array($this, 'errorHandler')); if (function_exists("pcntl_signal")) { pcntl_signal(SIGTERM, [$this, 'stopCommand']); pcntl_signal(SIGINT, [$this, 'stopCommand']); } else { } $this->isDebug = $input->getArgument('isDebug'); $port = $input->getOption('port'); $chat = $this->container->get('app.chat.handler'); $chat->setIsDebug($this->isDebug); $messageManager = new MessageManager($chat); $messageManager->setIsDebug($this->isDebug); $server = IoServer::factory(new HttpServer(new WsServer($messageManager)), $port); if ($this->isDebug) { $redis = $this->container->get('snc_redis.default'); $server->loop->addPeriodicTimer(5, function () use($redis, $messageManager) { $memory = memory_get_usage(); echo "Send messages. Redis value: " . $redis->get('value') . "\r\n"; $info = array(); $info['message'] = "Redis value: " . $redis->get('value') . "; Memory: " . $memory; $info['type'] = 'message'; $info['from'] = 'me'; $messageManager->sendAll(json_encode($info)); }); } $this->logMessage("Start server."); $server->run(); $this->logMessage("Finish execute daemon."); }
private function prepareData($context) { $c = ++$this->local_storage['counter']; $m = memory_get_usage(); $p = memory_get_peak_usage(); if ($p > $this->local_storage['prev_memory_peak']) { $this->local_storage['prev_memory_peak'] = $p; $this->local_storage['memory_peak_counter'] = $c; } $buffer = '<pre>'; $buffer .= 'Hello world! #' . $c . "\n"; $buffer .= 'Memory usage: ' . $m . "\n"; $buffer .= 'Peak Memory usage: ' . $p . "\n"; $buffer .= 'Memory usage last grew at request#' . $this->local_storage['memory_peak_counter'] . "\n\n"; $buffer .= "HEADERS:\n" . var_export($context['env'], true) . "\n"; $buffer .= "COOKIES:\n" . var_export($context['_COOKIE']->__toArray(), true) . "\n"; $buffer .= "GET:\n" . var_export($context['_GET'], true) . "\n"; if ($context['env']['REQUEST_METHOD'] === 'POST') { $buffer .= "POST:\n" . var_export($context['_POST'], true) . "\n"; $buffer .= "FILES:\n" . var_export($context['_FILES'], true) . "\n"; } elseif (!in_array($context['env']['REQUEST_METHOD'], array('GET', 'HEAD'))) { $buffer .= "BODY:\n" . var_export(stream_get_contents($context['stdin']), true) . "\n"; } $buffer .= '</pre>'; return $buffer; }
/** Allows you to time things and get memory usage @param name the name of the measure to be printed out with results. To get the timing between events, the name should be the same. */ static function measure($name = 'std') { $next = count(self::$measures[$name]); self::$measures[$name][$next]['time'] = microtime(true); self::$measures[$name][$next]['mem'] = memory_get_usage(); self::$measures[$name][$next]['peakMem'] = memory_get_peak_usage(); }
function profileOut($functionname) { $memory = memory_get_usage(); $time = $this->getTime(); global $wgDebugProfiling, $wgDebugFunctionEntry; if ($wgDebugFunctionEntry && function_exists('wfDebug')) { wfDebug(str_repeat(' ', count($this->mWorkStack) - 1) . 'Exiting ' . $functionname . "\n"); } $bit = array_pop($this->mWorkStack); if (!$bit) { wfDebug("Profiling error, !\$bit: {$functionname}\n"); } else { //if ($wgDebugProfiling) { if ($functionname == 'close') { $message = "Profile section ended by close(): {$bit[0]}\n"; wfDebug($message); $this->mStack[] = array($message, 0, 0, 0); } elseif ($bit[0] != $functionname) { $message = "Profiling error: in({$bit[0]}), out({$functionname})\n"; wfDebug($message); $this->mStack[] = array($message, 0, 0, 0); } //} $bit[] = $time; $bit[] = $memory; $this->mStack[] = $bit; } }
public function testClear() { $users = User::find('all'); $mem = memory_get_usage(); $users->clear(); $this->assertTrue(memory_get_usage() < $mem); }
/** * 记录和统计时间(微秒)和内存使用情况 * 使用方法: * <code> * G('begin'); // 记录开始标记位 * // ... 区间运行代码 * G('end'); // 记录结束标签位 * echo G('begin','end',6); // 统计区间运行时间 精确到小数后6位 * echo G('begin','end','m'); // 统计区间内存使用情况 * 如果end标记位没有定义,则会自动以当前作为标记位 * 其中统计内存使用需要 MEMORY_LIMIT_ON 常量为true才有效 * </code> * @param string $start 开始标签 * @param string $end 结束标签 * @param integer|string $dec 小数位或者m * @return mixed */ function G($start, $end = '', $dec = 4) { static $_info = array(); static $_mem = array(); if (is_float($end)) { // 记录时间 $_info[$start] = $end; } elseif (!empty($end)) { // 统计时间和内存使用 if (!isset($_info[$end])) { $_info[$end] = microtime(TRUE); } if (MEMORY_LIMIT_ON && $dec == 'm') { if (!isset($_mem[$end])) { $_mem[$end] = memory_get_usage(); } return number_format(($_mem[$end] - $_mem[$start]) / 1024); } else { return number_format($_info[$end] - $_info[$start], $dec); } } else { // 记录时间和内存使用 $_info[$start] = microtime(TRUE); if (MEMORY_LIMIT_ON) { $_mem[$start] = memory_get_usage(); } } }
/** * Set a benchmark stop point. * * @param string benchmark name * @return void */ public static function stop($name) { if (isset(self::$marks[$name]) and self::$marks[$name]['stop'] === FALSE) { self::$marks[$name]['stop'] = microtime(TRUE); self::$marks[$name]['memory_stop'] = function_exists('memory_get_usage') ? memory_get_usage() : 0; } }
public function getBase() { $db = new DbQuery(); $sql = $db->select()->from('Current_Coordinate')->where('Device_Id = 1 or Device_Id=3'); echo '<br>Select '; var_dump($sql->exec()); $sql = $db->select()->from('Organizations')->join('Organizations', 'Cities', 'City_Id'); echo '<br>Join '; var_dump($sql->exec()); echo '<br>Delete '; $sql_delete = $db->delete()->from('Cities')->where("Name_City = 'Альметьевск'"); var_dump($sql_delete->exec()); echo '<br>Insert '; $sql_insert = $db->insert('Cities', array('Name_City'), array('Бугульма')); var_dump($sql_insert->exec()); echo '<br>Update '; $sql_set = $db->update('Cities', "Name_City='Альметьевск'")->where("Name_City='Бугульма'"); var_dump($sql_set->exec()); echo '<br><br>'; echo "This model"; $db = new DbQuery('mssql'); $sql = $db->select()->from('NavMessages')->order('Id ASC'); echo '<br>Select '; var_dump($sql->exec()); echo "<br>Model memory : " . memory_get_usage() / 1000 . "<br>"; /**/ }