本文整理汇总了PHP中memory_get_usage函数的典型用法代码示例。如果您正苦于以下问题:PHP memory_get_usage函数的具体用法?PHP memory_get_usage怎么用?PHP memory_get_usage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了memory_get_usage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: memory_get_available
/**
* 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;
}
}
示例2: stop
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);
}
示例3: execute
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;
}
示例4: showTime
/**
* 显示运行时间、数据库操作、缓存次数、内存使用信息
* @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;
}
示例5: insert_query_info
/**
* 获得查询次数以及查询时间
*
* @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;
}
示例6: getLoadedProductCollectionpro
/**
* 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;
}
示例7: memory_usage
public static function memory_usage()
{
$bytes = memory_get_usage();
$kbytes = $bytes / 1024;
$mbytes = $kbytes / 1024;
return round($mbytes, 3);
}
示例8: showTime
/**
+----------------------------------------------------------
* 显示运行时间、数据库操作、缓存次数、内存使用信息
+----------------------------------------------------------
* @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;
}
示例9: on_complete
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";
}
示例10: execute
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();
}
示例11: init
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;
}
}
示例12: getMemoryUsage
/**
* 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);
}
示例13: interrupt_if_needed
/**
*
* @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;
}
示例14: detalleAction
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();
}
示例15: init_performance_info
/**
* 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;
}
}
}