Example: To be done before any scripts execute: $Timer = new Timer; $Timer->Start_Timer(); To be done after all scripts have executed: $timer->Stop_Timer(); $timer->Get_Elapsed_Time(int number_of_places);
Author: Charles Killian
Author: Hans Lellelid (hans@xmpl.org)
Example #1
0
 public function run()
 {
     # Only run once.
     if ($this->result !== null) {
         return $this;
     }
     # It's nice to have this as an implicit condition.
     if ($this->should_except) {
         $this->conditions[] = new Condition(function ($result) {
             return $result->exception() !== null;
         }, 'should throw exception');
     } else {
         $this->conditions[] = new Condition(function ($result) {
             return $result->exception() === null;
         }, 'should not throw exception');
     }
     ob_start();
     $value = null;
     $exception = null;
     $timer = new Timer();
     try {
         $value = call_user_func($this->closure, $this);
     } catch (\Exception $e) {
         $exception = $e;
     }
     $output = ob_get_clean();
     $this->result = new Result($value, $output, $timer->stop(), $exception);
     return $this;
 }
Example #2
0
 function parse()
 {
     if ($this->doParseRSS) {
         require_once "include/domit_rss/timer.php";
         $timer = new Timer();
         $success = false;
         $timer->start();
         if (!defined('DOMIT_RSS_INCLUDE_PATH')) {
             define('DOMIT_RSS_INCLUDE_PATH', dirname(__FILE__) . "/");
         }
         switch ($this->rssparser) {
             case "domit_rss_lite":
                 require_once DOMIT_RSS_INCLUDE_PATH . 'xml_domit_rss_lite.php';
                 $this->rssdoc = new xml_domit_rss_document_lite($this->rssurl);
                 break;
             case "domit_rss":
                 require_once DOMIT_RSS_INCLUDE_PATH . 'xml_domit_rss.php';
                 $this->rssdoc = new xml_domit_rss_document($this->rssurl);
                 break;
         }
         // switch
         $timer->stop();
         $this->displayNew();
         echo "<br /><br />Time elapsed: " . $timer->getTime() . "seconds<br /><br />\n";
     }
 }
Example #3
0
function myquery($query)
{
    global $time_mysql_query;
    global $numsql;
    global $debuginfo;
    $backtrace = debug_backtrace();
    $back1 = $backtrace;
    $backtrace = " in : " . $backtrace[0]["file"] . ", on line: " . $backtrace[0]["line"] . "";
    if (debug_run == 1) {
        $MyTimerSQL = new Timer();
        $MyTimerSQL->Init();
        //$result = mysql_query($query) or trigger_error(mysql_errno() . ": <b>" . mysql_error() . $backtrace . format_query($query) , E_USER_ERROR);
        $result = mysql_query($query) or send_error(mysql_errno() . ": <b>" . mysql_error() . $backtrace . "<br /><br /><p>Query: " . $query . "</p>", $backtrace);
        $exec_time_mysql = $MyTimerSQL->GetTime(5);
        $GLOBALS['numsql']++;
        $time_mysql_query += $exec_time_mysql;
        $GLOBALS['debuginfo'] .= '<tr><td>' . $query . '</td><td><span style="color:#C0FFFF">' . $exec_time_mysql . '</span></td><td><span style="color:lightgrey">' . $backtrace . '</span></tr>';
        if (isset($GLOBALS['debug'][$back1[0]['file']])) {
            $GLOBALS['debug'][$back1[0]['file']]['time_sql'] += $exec_time_mysql;
            $GLOBALS['debug'][$back1[0]['file']]['count_sql'] += 1;
        }
    } else {
        $result = mysql_query($query);
    }
    /*
    	if (strpos($query,"EXP")!==FALSE AND strpos($query,"game_users")!==FALSE AND strpos($query,"UPDATE")!==FALSE)
    	{
    		mysql_query("INSERT INTO query_log (query,timestamp,filename) VALUES ('$query',".time().",'$backtrace')");
    	}
    */
    return $result;
}
 private static function populateCharacters($db)
 {
     global $baseDir;
     $timer = new Timer();
     $maxTime = 65 * 1000;
     // Reset 222's that are over a week old
     $db->execute("update zz_api set errorCode = 0 where errorCode = 222 and lastValidation <= date_sub(now(), interval 7 day)");
     $apiCount = $db->queryField("select count(*) count from zz_api where errorCode not in (203, 220, 222) and lastValidation <= date_add(now(), interval 1 minute)", "count", array(), 0);
     if ($apiCount == 0) {
         return;
     }
     $fetchesPerSecond = 25;
     $iterationCount = 0;
     while ($timer->stop() < $maxTime) {
         $keyIDs = $db->query("select distinct keyID from zz_api where errorCode not in (203, 220, 222) and lastValidation < date_sub(now(), interval 2 hour)\r\n\t\t\t\t\torder by lastValidation, dateAdded desc limit 100", array(), 0);
         foreach ($keyIDs as $row) {
             if (Util::isMaintenanceMode()) {
                 return;
             }
             $keyID = $row["keyID"];
             $m = $iterationCount % $fetchesPerSecond;
             $db->execute("update zz_api set lastValidation = date_add(lastValidation, interval 5 minute) where keyID = :keyID", array(":keyID" => $keyID));
             $command = "flock -w 60 {$baseDir}/cache/locks/populate.{$m} php5 {$baseDir}/cli.php apiFetchCharacters " . escapeshellarg($keyID);
             //Log::log("$command");
             exec("{$command} >/dev/null 2>/dev/null &");
             $iterationCount++;
             if ($iterationCount % $fetchesPerSecond == 0) {
                 sleep(1);
             }
         }
         sleep(1);
     }
 }
 public function dispatchLoopShutdown()
 {
     //
     // Force output to be sent - we need the client to have the page before
     // we start flushing progress bar updates
     //
     $app = AppController::getInstance();
     $req = $app->getRequest();
     $resp = $app->getResponse();
     $resp->sendResponse();
     $resp->clearContent();
     //
     // Do reindexing
     //
     if ($req->isLoggedIn() && $req->user->canDoAction('can_do_search_reindex')) {
         set_time_limit(3600 * 8);
         $o_db = new Db();
         $t_timer = new Timer();
         $o_dm = Datamodel::load();
         $va_table_names = $o_dm->getTableNames();
         $vn_tc = 0;
         foreach ($va_table_names as $vs_table) {
             if ($o_instance = $o_dm->getInstanceByTableName($vs_table)) {
                 if ($o_instance->isHierarchical()) {
                     if (!$o_instance->rebuildAllHierarchicalIndexes()) {
                         $o_instance->rebuildHierarchicalIndex();
                     }
                 }
                 caIncrementHierachicalReindexProgress(_t('Rebuilding hierarchical index for %1', $o_instance->getProperty('NAME_PLURAL')), $t_timer->getTime(2), memory_get_usage(true), $va_table_names, $o_instance->tableNum(), $o_instance->getProperty('NAME_PLURAL'), $vn_tc + 1);
             }
             $vn_tc++;
         }
         caIncrementHierachicalReindexProgress(_t('Index rebuild complete!'), $t_timer->getTime(2), memory_get_usage(true), $va_table_names, null, null, sizeof($va_table_names));
     }
 }
Example #6
0
/**
 * Returns single benchmark time in seconds
 *
 * @param string $benchmarkLambdaFunction Benchmark lambda function
 * @param array $benchmarkFunctionArgumentsArray Benchmark arguments array
 *
 * @return float
 */
function getSingleBenchmarkTimeSecs($benchmarkLambdaFunction, array $benchmarkFunctionArgumentsArray)
{
    $autoStartTimer = 1;
    $timer = new Timer($autoStartTimer);
    call_user_func_array($benchmarkLambdaFunction, $benchmarkFunctionArgumentsArray);
    return $timer->get();
}
Example #7
0
 /**
  * Open a message store.
  *
  * @param string $identity The identity to open as an URI
  */
 function open($identity)
 {
     $file = parse_url($identity, PHP_URL_HOST);
     // Set up the paths and objects we need
     $this->mbpath = config::get(FilesystemMailStorage::KEY_STORAGE_PATH, BASE_PATH . 'cache') . '/' . $file . '.xml';
     $this->lockpath = config::get(FilesystemMailStorage::KEY_STORAGE_PATH, BASE_PATH . 'cache') . '/' . $file . '.lock';
     $this->mbox = new DOMDocument('1.0');
     // Primitive locking for the win :) This should be more than enough
     // for whoever decides to use this. Will probably not be too good to
     // the disk under heavy load.
     $t = new Timer(true);
     $to = config::get(FilesystemMailStorage::KEY_LOCK_TIMEOUT, FilesystemMailStorage::DEF_LOCK_TIMEOUT);
     console::debugEx(LOG_DEBUG, __CLASS__, "Acquiring lock...");
     while (file_exists($this->lockpath)) {
         usleep(100000);
         if ($t->getElapsed() > $to) {
             throw new MailException("Timed out waiting for lock.");
         }
     }
     unset($t);
     $this->lock = fopen($this->lockpath, 'w');
     // Check if the mailbox exists
     if (file_exists($this->mbpath)) {
         $this->mbox->load($this->mbpath);
         console::debugEx(LOG_DEBUG, __CLASS__, "Loaded mailbox %s", $this->mbpath);
     } else {
         console::debugEx(LOG_DEBUG, __CLASS__, "Created new mailbox %s", $this->mbpath);
         $this->mbox->appendChild($this->mbox->createElement('mailbox'));
     }
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 public function start(Timer $timer)
 {
     if (!isset($this->timers[$timer])) {
         $interval = $timer->getInterval();
         $event = $this->loop->timer($interval, $timer->isPeriodic() ? $interval : 0, $this->callback, $timer);
         $this->timers[$timer] = $event;
     }
 }
Example #9
0
File: Xml.php Project: rajnishp/bjs
 /**
  * Try to emulate SAX type serialization, because otherwise it goes out of memory
  * @param $data
  * @param $output Sets the output to this variable
  * @param $clear_data If set, $data is cleared once serialization is done
  * @return unknown_type
  */
 function serializeLowMemory(&$data, &$output, $clear_data = false, $batch_size = 1000)
 {
     if ($this->serializer == false) {
         $serializer_options = array('addDecl' => FALSE, 'encoding' => 'ISO-8859-1', 'indent' => '  ', 'rootName' => 'item', 'defaultTagName' => 'item');
         $this->serializer = new XML_Serializer($serializer_options);
     }
     list($temp_file_name, $http) = Util::getTemporaryFile('xml-serialize', 'xml');
     $this->logger->debug("Using temporary file for XML Serialization: {$temp_file_name}");
     $fh = fopen($temp_file_name, 'w');
     fwrite($fh, "<?xml version='1.0' encoding='ISO-8859-1'?>\n<root>\n");
     if (Util::is_assoc($data)) {
         foreach ($data as $top_level_tag_key => &$data_value) {
             $first = true;
             fwrite($fh, "<{$top_level_tag_key}>\n");
             if (is_array($data_value)) {
                 $count = 0;
                 $string = "";
                 $timer = new Timer('SerializationTimer');
                 $timer->start();
                 foreach ($data_value as $second_level_key => &$second_level_value) {
                     $string .= $this->serializeXml($second_level_value) . "\n";
                     $count++;
                     if ($count % $batch_size == 0) {
                         $timer->stop();
                         fwrite($fh, $string);
                         $string = "";
                         $this->logger->debug("{$top_level_tag_key} > Serialized upto row - " . $count++ . ". Time Taken : " . $timer->getLastLapTime() . "s. Current Memory usage: " . memory_get_usage() / 1000000 . "MB");
                         $timer->start();
                     }
                     if ($first) {
                         $this->logger->debug("{$top_level_tag_key} > XML Serialization Sample Data : Key is {$second_level_key}\nValue is " . print_r($second_level_value, true));
                         $first = false;
                     }
                     //if clear data is set, clear the second level value
                     if ($clear_data) {
                         $second_level_value = false;
                     }
                     //fflush($fh);
                 }
                 //the last batch might not be complete
                 if ($string != "") {
                     $timer->stop();
                     fwrite($fh, $string);
                     $string = "";
                 }
             }
             fwrite($fh, "</{$top_level_tag_key}>\n");
             if ($clear_data) {
                 $data_value = false;
             }
         }
     }
     fwrite($fh, "\n</root>");
     fclose($fh);
     $output = file_get_contents($temp_file_name);
 }
 public function runPlugin($input = array())
 {
     $badContent = 1;
     $goodContent = 1;
     if (!isset($input['tracerouteFailDomain'])) {
         $input['tracerouteFailDomain'] = '';
     }
     if (!isset($input['followRedirects'])) {
         $input['followRedirects'] = 1;
     }
     $input['followRedirects'] = (bool) $input['followRedirects'];
     for ($i = $input['attempts']; $i <= $input['attempts']; $i++) {
         $output = Plugin::$output;
         ///set defaults for all output
         $t = new Timer();
         $t->start();
         $output['returnContent'] = HttpContentPlugin::doHTTPGet($input['url'], $input['maxConnectTimeoutSeconds'], $input['maxRequestTimeoutSeconds'], $input['followRedirects']);
         //			echo $output['returnContent'];
         $output['responseTimeMs'] = (int) $t->stop();
         $output['measuredValue'] = $output['returnContent'];
         if (trim($input['goodContent']) != '') {
             $goodContent = strpos($output['returnContent'], $input['goodContent']) === false ? 0 : 1;
         }
         if (trim($input['badContent']) != '') {
             $badContent = strpos($output['returnContent'], $input['badContent']) === false ? 1 : 0;
         }
         //default to down
         $output['currentStatus'] = 0;
         //if its already bad, then its bad.
         if ($goodContent + $badContent == 2) {
             $output['currentStatus'] = 1;
         }
         if ($output['currentStatus'] == 1) {
             //we've got what we wanted
             break;
         } else {
             //else keep going till we do or hit max attempts
             if (isset($input['attemptWait']) && $input['attemptWait'] !== 0) {
                 usleep($input['attemptWait'] * 1000);
             }
         }
     }
     //html email
     $output['htmlEmail'] = 1;
     if ($output['currentStatus'] == 0 && $input['tracerouteFailDomain'] != '') {
         $tmpfname = tempnam("/tmp", "phpMonitorHTTPContent");
         // do here something
         $cmd = '/usr/sbin/mtr --report --report-cycles 5 ' . $input['tracerouteFailDomain'] . ' > ' . $tmpfname . ' 2>&1';
         exec($cmd);
         $return = file_get_contents($tmpfname);
         unlink($tmpfname);
         //			echo $cmd;
         $output['returnContent'] = $output['returnContent'] . "\n\n<pre>{$return}</pre>";
     }
     return $output;
 }
Example #11
0
 /**
  * {@inheritdoc}
  */
 public function start(Timer $timer)
 {
     $flags = Event::TIMEOUT;
     if ($timer->isPeriodic()) {
         $flags |= Event::PERSIST;
     }
     $event = new Event($this->base, -1, $flags, $this->callback, $timer);
     $this->timers[$timer] = $event;
     $event->add($timer->getInterval());
 }
Example #12
0
 /**
  *
  *
  *
  *
  * @return Timer
  */
 public static function Start()
 {
     static $instance;
     if (!isset($instance)) {
         $instance = new Timer();
     }
     $time = $instance->GetMicrotime();
     array_push($instance->startTimes, $time);
     return $instance;
 }
Example #13
0
 /**
  * {@inheritdoc}
  */
 public function start(Timer $timer)
 {
     if (!isset($this->timers[$timer])) {
         $handle = \uv_timer_init($this->loopHandle);
         $interval = $timer->getInterval() * self::MILLISEC_PER_SEC;
         \uv_timer_start($handle, $interval, $timer->isPeriodic() ? $interval : 0, $this->callback);
         $this->timers[$timer] = $handle;
         $this->handles[(int) $handle] = $timer;
     }
 }
 function parse()
 {
     if ($this->xmlaction != null) {
         require_once "timer.php";
         $timer = new Timer();
         $success = false;
         $this->saxparser == "saxy" ? $parseSAXY = true : ($parseSAXY = false);
         $timer->start();
         switch ($this->domparser) {
             case "domit":
                 //change this to the domit path
                 require_once 'xml_domit_parser.php';
                 $this->xmldoc =& new DOMIT_Document();
                 $this->xmldoc->expandEmptyElementTags(true);
                 $this->xmldoc->setNamespaceAwareness(true);
                 break;
             case "domitlite":
                 //change this to the domit lite path
                 require_once 'xml_domit_lite_parser.php';
                 $this->xmldoc =& new DOMIT_Lite_Document();
                 break;
         }
         // switch
         switch ($this->xmlaction) {
             case "parsefile":
                 $success = $this->xmldoc->loadXML($this->xmlfile, $parseSAXY);
                 break;
             case "parseurl":
                 $success = $this->xmldoc->loadXML("http://" . $this->xmlurl, $parseSAXY);
                 break;
             case "parsetext":
                 $success = $this->xmldoc->parseXML($this->xmltext, $parseSAXY);
                 break;
         }
         $timer->stop();
         if ($success) {
             echo "<br /><br />Time elapsed: " . $timer->getTime() . "seconds<br /><br />\n";
             if ($this->xmloutput == "tostring") {
                 echo $this->xmldoc->toString(true);
             } else {
                 if ($this->xmloutput == "tonormalizedstring") {
                     echo $this->xmldoc->toNormalizedString(true);
                 } else {
                     if ($this->xmloutput == "toarray") {
                         echo "<pre>\n";
                         print_r($this->xmldoc->toArray());
                         echo "</pre>\n";
                     }
                 }
             }
         } else {
             echo "<br /><br />Parsing error: xml document may be invalid or malformed.\n";
         }
     }
 }
Example #15
0
 /**
  * Return a tree of time periods from a Timer
  *
  * @param Timer $timer Timer object
  * @return array
  */
 public function buildTree(Timer $timer)
 {
     $times = $timer->getTimes();
     if (!isset($times[':end'])) {
         $times[':end'] = microtime();
     }
     $begin = $this->findBeginTime($times);
     $end = $this->findEndTime($times);
     $this->total = $this->diffMicrotime($begin, $end);
     return $this->analyzePeriod('', $times);
 }
 public function testSaveSimple()
 {
     //Logger::getInstance()->on();
     YuppLoader::load('core.support', 'Timer');
     $timer = new Timer();
     $timer->start();
     $bot = new Botella(array("material" => "vidrio", "capacidad" => 1.5, "tapaRosca" => true));
     $this->assert($bot->save(), 'Test guardar 1 ' . print_r($bot->getErrors(), true));
     $timer->stop();
     echo 'Time: ' . $timer->getElapsedTime() . '<br/>';
     //Logger::getInstance()->off();
 }
 public final function run(SystemUnderTest $systemUnderTest, $times)
 {
     $systemUnderTest->warmUp();
     $this->warmUp($systemUnderTest);
     $timer = new Timer($this->getName());
     $systemUnderTest->start();
     for ($i = 0; $i < $times; $i++) {
         $this->performTest($systemUnderTest, $i);
     }
     $systemUnderTest->end();
     return $timer->getElapsedTime() * 1000;
 }
Example #18
0
 public function testStopChildren()
 {
     // Init
     $timer = new Timer();
     // Process
     $timer->start('mysql.sql.query.response.parsing', true);
     usleep(50000);
     $timer->stop('mysql.sql');
     usleep(50000);
     $value = $timer('mysql.sql.query.response.parsing');
     // Assert
     $this->assertEquals(true, $value > 0.045 && $value < 0.55);
 }
Example #19
0
 /**
  * Lazy loading of Timer class instance.
  *
  * @return Timer
  */
 public static function instance()
 {
     if (self::$instance === null) {
         self::$instance = new self();
     }
     return self::$instance;
 }
Example #20
0
 function boot()
 {
     if (!defined('APP_ROOT')) {
         define('APP_ROOT', dirname(dirname(__FILE__)));
     }
     Timer::start();
 }
 public function run(Promise &$promise)
 {
     $urlInfo = parse_url($this->url);
     $timeout = $this->timeout;
     if (!isset($urlInfo['port'])) {
         $urlInfo['port'] = 80;
     }
     $cli = new \swoole_http_client($urlInfo['host'], $urlInfo['port']);
     $cli->set(array('timeout' => $timeout, 'keepalive' => 0));
     $cli->on("error", function ($cli) use(&$promise) {
         Timer::del($cli->sock);
         $promise->accept(['http_data' => null, 'http_error' => 'Connect error']);
     });
     $cli->on("close", function ($cli) use(&$promise) {
     });
     $cli->execute($this->url, function ($cli) use(&$promise) {
         Timer::del($cli->sock);
         $cli->isDone = true;
         $promise->accept(['http_data' => $cli->body]);
     });
     $cli->isConnected = false;
     if (!$cli->errCode) {
         Timer::add($cli->sock, $this->timeout, function () use($cli, &$promise) {
             @$cli->close();
             if ($cli->isConnected) {
                 $promise->accept(['http_data' => null, 'http_error' => 'Http client read timeout']);
             } else {
                 $promise->accept(['http_data' => null, 'http_error' => 'Http client connect timeout']);
             }
         });
     }
 }
Example #22
0
 public function extractPage($pageID, $pageTitle, $pageSource)
 {
     $this->extractor->setPageURI($pageID);
     if (!$this->extractor->isActive()) {
         return $result = new ExtractionResult($pageID, $this->extractor->getLanguage(), $this->getExtractorID());
     }
     Timer::start($this->extractor->getExtractorID());
     $result = $this->extractor->extractPage($pageID, $pageTitle, $pageSource);
     Timer::stop($this->extractor->getExtractorID());
     Timer::start('validation');
     //$this->extractor->check();
     if (Options::getOption('validateExtractors')) {
         ValidateExtractionResult::validate($result, $this->extractor);
     }
     Timer::stop('validation');
     Statistics::increaseCount($this->extractor->getExtractorID(), 'created_Triples', count($result->getTriples()));
     Statistics::increaseCount('Total', 'created_Triples', count($result->getTriples()));
     if ($this->extractor->isGenerateOWLAxiomAnnotations()) {
         $triples = $result->getTriples();
         if (count($triples) > 0) {
             foreach ($triples as $triple) {
                 $triple->addDCModifiedAnnotation();
                 $triple->addExtractedByAnnotation($this->extractor->getExtractorID());
             }
         }
     }
     return $result;
 }
Example #23
0
 public static function getInstance()
 {
     if (self::$instance == NULL) {
         self::$instance = new Timer();
     }
     return self::$instance;
 }
 public function getSource($pageID)
 {
     Timer::start('LiveFromFileCollection');
     $content = file_get_contents($this->currentArticleFile);
     Timer::stop('LiveFromFileCollection');
     return $content;
 }
Example #25
0
 /**
  * Provided a URL, will return an array representing the feed item for that
  * URL.  A feed item contains the content, url, simplepie object, and failure
  * status for the URL passed.  Handles caching of content requests.
  *
  * @return array
  * @author Jared Lang
  **/
 protected static function __new_feed($url)
 {
     $timer = Timer::start();
     require_once THEME_DIR . '/third-party/simplepie.php';
     $simplepie = null;
     $failed = False;
     $cache_key = 'feedmanager-' . md5($url);
     $content = get_site_transient($cache_key);
     if ($content === False) {
         $content = @file_get_contents($url);
         if ($content === False) {
             $failed = True;
             $content = null;
             error_log('FeedManager failed to fetch data using url of ' . $url);
         } else {
             set_site_transient($cache_key, $content, self::$cache_length);
         }
     }
     if ($content) {
         $simplepie = new SimplePie();
         $simplepie->set_raw_data($content);
         $simplepie->init();
         $simplepie->handle_content_type();
         if ($simplepie->error) {
             error_log($simplepie->error);
             $simplepie = null;
             $failed = True;
         }
     } else {
         $failed = True;
     }
     $elapsed = round($timer->elapsed() * 1000);
     debug("__new_feed: {$elapsed} milliseconds");
     return array('content' => $content, 'url' => $url, 'simplepie' => $simplepie, 'failed' => $failed);
 }
Example #26
0
 public static function initResource($inifile)
 {
     //Timer::start("a");
     $arr = parse_ini_file($inifile);
     /*
     		Timer::stop("a");
     		Timer::start("b");
     		$p = new Properties();
     		$fp = fopen($inifile.'2','r');
     		$p->load($fp);
     		
     		//print_r($p->propertyNames());
     		Timer::stop("b");
     		Timer::printTime(10);
     		die();
     */
     if (!is_array($arr) || !count($arr) > 0) {
         die("core/ResourcePool : inifile " . $inifile . " not found\n");
     }
     Timer::start('ResourcePool::init::' . $class);
     $class = new ReflectionClass($arr['className']);
     $resourceInstance = $class->newInstance($arr);
     $resourceInstance->init();
     self::$resources = $resourceInstance;
     Timer::stop('ResourcePool::init::' . $class);
     //$resourceInstance
     //$resourceInstance->setStatus($status);
 }
Example #27
0
 /**
  * [Kind of controller's destructor. Called when child's work is done]
  * @return [type] [description]
  */
 public function displayView()
 {
     $output = self::stopCapturing();
     if (strlen($output) === 0) {
         Debug::write("No output from controller was detected. No additionnal action will be done on HTML content", 0);
     } else {
         $this->view->setContent("%%@MAIN CONTENT%%", $output);
     }
     $this->view->display();
     /**
      * Breaking the DOM for credits or stats
      */
     if ($GLOBALS['config']['website']['display_credits'] === true || $GLOBALS['config']['website']['display_stats'] === true) {
         echo '<div style="border-top: 1px ridge black;"><p style="text-align:center;font-size:12px;">';
         if ($GLOBALS['config']['website']['display_credits'] === true) {
             echo $GLOBALS['config']['website']['name'] . ' v' . (is_numeric($GLOBALS['config']['website']['version']) ? number_format($GLOBALS['config']['website']['version'], 1) : $GLOBALS['config']['website']['version']) . ' ' . $GLOBALS['config']['website']['branch'] . ', powered by SPF v' . (is_numeric($GLOBALS['config']['framework']['version']) ? number_format($GLOBALS['config']['framework']['version'], 1) : $GLOBALS['config']['framework']['version']) . ' ' . $GLOBALS['config']['framework']['branch'] . '<br />';
         }
         if ($GLOBALS['config']['website']['display_stats'] === true) {
             $time = round(Timer::getTimeFrom("Start"), 5);
             if ($time >= 1) {
                 $unit = 's';
                 $time = round($time, 1);
             } else {
                 $unit = 'ms';
                 $time = round($time * 1000, 5);
             }
             if ($this->db !== null) {
                 echo 'Number of SQL requests : ' . $this->db->getStats() . ' - Page generated in ' . $time . $unit . '<br />';
             }
         }
         echo '</p></div>';
     }
 }
 /**
  * Runtime of Master process
  * @return void
  */
 public function run()
 {
     Daemon::$process = $this;
     $this->prepareSystemEnv();
     class_exists('Timer');
     // ensure loading this class
     gc_enable();
     $this->eventBase = event_base_new();
     $this->registerEventSignals();
     FS::initEvent();
     $this->fileWatcher = new FileWatcher();
     $this->workers = new ThreadCollection();
     $this->collections['workers'] = $this->workers;
     Daemon::$appResolver = (require Daemon::$config->path->value);
     $this->IPCManager = Daemon::$appResolver->getInstanceByAppName('IPCManager');
     Daemon::$appResolver->preload(true);
     $this->callbacks = new SplStack();
     $this->spawnWorkers(min(Daemon::$config->startworkers->value, Daemon::$config->maxworkers->value));
     Timer::add(function ($event) use(&$cbs) {
         $self = Daemon::$process;
         static $c = 0;
         ++$c;
         if ($c > 0xfffff) {
             $c = 1;
         }
         if ($c % 10 == 0) {
             $self->workers->removeTerminated(true);
             gc_collect_cycles();
         } else {
             $self->workers->removeTerminated();
         }
         if (isset(Daemon::$config->mpm->value) && is_callable(Daemon::$config->mpm->value)) {
             call_user_func(Daemon::$config->mpm->value);
         } else {
             // default MPM
             $state = Daemon::getStateOfWorkers($self);
             if ($state) {
                 $n = max(min(Daemon::$config->minspareworkers->value - $state['idle'], Daemon::$config->maxworkers->value - $state['alive']), Daemon::$config->minworkers->value - $state['alive']);
                 if ($n > 0) {
                     Daemon::log('Spawning ' . $n . ' worker(s).');
                     $self->spawnWorkers($n);
                     event_base_loopbreak($self->eventBase);
                 }
                 $n = min($state['idle'] - Daemon::$config->maxspareworkers->value, $state['alive'] - Daemon::$config->minworkers->value);
                 if ($n > 0) {
                     Daemon::log('Stopping ' . $n . ' worker(s).');
                     $self->stopWorkers($n);
                 }
             }
         }
         $event->timeout();
     }, 1000000.0 * Daemon::$config->mpmdelay->value, 'MPM');
     while (!$this->breakMainLoop) {
         while (!$this->callbacks->isEmpty()) {
             call_user_func($this->callbacks->shift(), $this);
         }
         event_base_loop($this->eventBase);
     }
 }
 public function delTimer($interval, $userFlag, $obj)
 {
     // 从Timer静态类中清楚该定时器
     Timer::delTimer($interval, $userFlag);
     if (Timer::getCount($interval) === 0) {
         $this->server->delTimer($interval);
     }
 }
Example #30
0
 public function testCanDetectEnd()
 {
     $this->assertFalse($this->timer->hasEnded([]));
     $this->timer->begin([]);
     $this->assertFalse($this->timer->hasEnded([]));
     $this->timer->end([]);
     $this->assertTrue($this->timer->hasEnded([]));
     $this->timer->end(['1', 'a']);
     $this->assertTrue($this->timer->hasEnded(['1', 'a']));
 }