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); }
/** * Tests duration measuring. */ public function testDuration() { $mt = microtime(true); $name = Timer::start(); $delta = Timer::stop($name); $outerDelta = microtime(true) - $mt; // Measured time is greater than 0 $this->assertGreaterThan(0, $delta); // Measured time is less than the time between the two function calls $this->assertLessThan($outerDelta, $delta); // Non-existent timer $this->assertSame(0, Timer::stop('foo')); // Start 4 timers $names = array('foo', 'bar', 'tmp', 'ohai'); $times = array_fill_keys($names, 0); foreach ($names as $name) { Timer::start($name); } // End them in reverse order foreach (array_reverse($names) as $name) { $times[$name] = Timer::stop($name); } // The measured time is supposed to be in descending order foreach ($names as $i => $name) { $this->assertGreaterThan(0, $times[$name]); if ($i > 0) { $this->assertLessThan($times[$names[$i - 1]], $times[$name]); } } }
/** * 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); }
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; }
public function getSource($pageID) { Timer::start('LiveFromFileCollection'); $content = file_get_contents($this->currentArticleFile); Timer::stop('LiveFromFileCollection'); return $content; }
function boot() { if (!defined('APP_ROOT')) { define('APP_ROOT', dirname(dirname(__FILE__))); } Timer::start(); }
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"; } }
/** * Start * @param digits number of decimals to calculate * @return nothing */ function start($digits = null) { if (!empty($digits)) { self::$digits = $digits; } self::$start = microtime(true); self::$started = true; }
public function elapsedTimeGreaterThanZeroUsingStartAndStop() { $fixture = new Timer(); $fixture->start(); usleep(100 * 1000); $fixture->stop(); $elapsed = $fixture->elapsedTime(); $this->assertTrue($elapsed > 0.0, 'Elapsed time should be greater than zero'); }
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; }
/** * Triggers the ExtractionJob * @param $job: An ExtractionJob */ public function execute($job) { $language = $job->getPageCollection()->getLanguage(); // Initialize Extractors and Destination foreach (new ArrayObject($job->getExtractionGroups()) as $group) { $group->getDestination()->start(); foreach (new ArrayObject($group->getExtractors()) as $extractor) { $extractor->start($language); } } $this->log(DEBUG, "extractors started"); // Extract content from WikiPedia Pages // The PageTitleIterator loops over all pages from a PageCollection foreach ($job->getPageTitleIterator() as $pageTitle) { Timer::start(get_class($job->getPageCollection()) . '::getSource'); $pageSource = $job->getPageCollection()->getSource($pageTitle); Timer::stop(get_class($job->getPageCollection()) . '::getSource'); $pageID = $this->getPageID($pageTitle, $pageSource, $language); if ($pageID === false || $pageID == NULL) { continue; } $this->log(DEBUG, "begin page extraction"); // Extract the content and pass it to the Destination foreach (new ArrayObject($job->getExtractionGroups()) as $group) { $destination = $group->getDestination(); foreach (new ArrayObject($group->getExtractors()) as $extractor) { $this->log(DEBUG, "extractPage: " . $extractor->getExtractorID()); $result = $extractor->extractPage($pageID, $pageTitle, $pageSource); Timer::start('destination:accept'); $destination->accept($result); Timer::stop('destination:accept'); } //end foreach } //end outer foreach } // Close Destinations and Extractors foreach (new ArrayObject($job->getExtractionGroups()) as $group) { Timer::start('destination:finish'); $group->getDestination()->finish(); Timer::stop('destination:finish'); // Optional MetaInformation is stored in MetaDestination // Currently only used for InfoboxExtraction for predicates $metaDestination = $group->getMetaDestination(); if ($metaDestination != null) { $metaDestination->start(); foreach (new ArrayObject($group->getExtractors()) as $extractor) { $result = $extractor->finish(); if ($result != null) { $metaDestination->accept($result); } } $metaDestination->finish(); } } }
/** * 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); }
/** * Run benchmark. * * @throws BenchEx * * @return Bench */ public function run() { foreach ($this->benchmarks as $name => $benchmark) { $this->timer->start($name); $benchmark($this->iterations); $this->timer->stop($name); } $this->createSummary(); return $this; }
public function testElapsedTimeGivesSameResultAsTimersArray() { $timer = new Timer(); $timer->start('test1'); sleep(1); $timer->stop('test1'); $timers = $timer->getTimers(); $expected = $timers['test1']['duration']; $this->assertEquals($expected, $timer->getElapsedTime('test1')); }
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"; } } }
public function testToString() { $this->object->start(); $this->object->stop(); ob_start(); echo $this->object; $content = ob_get_contents(); ob_end_clean(); $this->assertInternalType("string", $content); $this->assertNotEmpty($content); }
/** * Main program. * * @param array $args Command-line arguments. * @return integer Zero on success; non-zero on failure. */ public static function main($args) { $status = 0; printf("3\n"); printf("n\n"); printf("fib1 s\n"); printf("fib2 s\n"); for ($i = 0; $i < 48; ++$i) { $timer = new Timer(); $timer->start(); $result = fibonacci($i); $timer->stop(); $time1 = $timer->getElapsedTime(); $timer->start(); $result = fibonacci2($i); $timer->stop(); $time2 = $timer->getElapsedTime(); printf("%d\t%f\t%f\n", $i, $time1, $time2); } return $status; }
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(); }
function boot() { if (!defined('APP_ROOT')) { define('APP_ROOT', dirname(dirname(__FILE__))); } self::$tmp_path = APP_ROOT . '/tmp'; // initialize preference system include APP_ROOT . '/framework/lib/preferences.php'; self::$prefs = new PreferenceCollection(array(self::$tmp_path)); self::$prefs->read('cache', true, self::$tmp_path); Timer::start(); }
public function query($query){ if(!$this->wasInititialized){ $this->log('warn', $this->id." mysql resource was not intialized"); } Timer::start(get_class($this).""); $now = microtime(true); $result = mysql_query($query, $this->connection); $needed = (microtime(true)-$now); $this->log('debug', "query needed ".$needed. " msec : ".$query); Timer::stop(get_class($this).""); return $result; }
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); }
public static function getGlobalDbObj(array $args = array()) { global $_DB_OBJ; $prefix = $args['prefix']; if (isset($_DB_OBJ[$prefix]) == false) { // requirePackage('mysqli', 2); $timer = Timer::start('Mysqli Loading ... ' . $prefix . '_HOST'); $databaseInterfaceClass = 'MysqliConnect'; $params = array('host' => constant($prefix . '_HOST'), 'username' => constant($prefix . '_USER'), 'password' => constant($prefix . '_PASS'), 'database' => constant($prefix . '_DB')); $_DB_OBJ[$prefix] = new $databaseInterfaceClass($params); Timer::stop($timer); // echo 'Getting new db connection. ' . $prefix . ', ' . print_r($params, true) . "\n"; } return $_DB_OBJ[$prefix]; }
public function httpget($url) { $s = curl_init(); Timer::start(get_class($this) . ""); curl_setopt($s, CURLOPT_URL, $url); curl_setopt($s, CURLOPT_RETURNTRANSFER, true); curl_setopt($s, CURLOPT_BINARYTRANSFER, true); $result = curl_exec($s); if ($result === false) { Logger::warn($url . ' returned faulty result ' . curl_error()); } Timer::stop(get_class($this) . ""); //echo $result; return $result; }
public static function init($cli) { register_shutdown_function(['\\Thin\\Bootstrap', 'finish']); Timer::start(); lib('app'); forever(); $storage_dir = STORAGE_PATH; if (!is_writable(STORAGE_PATH)) { die('Please give 0777 right to ' . STORAGE_PATH); } if (!is_dir(CACHE_PATH)) { File::mkdir(CACHE_PATH); } $dir = APPLICATION_PATH; Config::set('app.module.dir', APPLICATION_PATH); Config::set('mvc.dir', APPLICATION_PATH); Config::set('app.module.dirstorage', $dir . DS . 'storage'); Config::set('app.module.assets', $dir . DS . 'assets'); Config::set('app.module.config', $dir . DS . 'config'); Config::set('dir.raw.store', $storage_dir . DS . 'db'); Config::set('dir.ardb.store', $storage_dir . DS . 'db'); Config::set('dir.ephemere', $storage_dir . DS . 'ephemere'); Config::set('dir.flight.store', $storage_dir . DS . 'flight'); Config::set('dir.flat.store', $storage_dir . DS . 'flat'); Config::set('dir.cache.store', $storage_dir . DS . 'cache'); Config::set('dir.nosql.store', $storage_dir . DS . 'nosql'); Config::set('dir.module.logs', $storage_dir . DS . 'logs'); path('module', $dir); path('pages', $dir . DS . 'app' . DS . 'pages'); path('layouts', $dir . DS . 'app' . DS . 'layouts'); path('store', $storage_dir); path('config', Config::get('app.module.config')); path('cache', CACHE_PATH); loaderProject('entity'); loaderProject('system'); Alias::facade('DB', 'EntityProject', 'Thin'); Alias::facade('System', 'SystemProject', 'Thin'); System::Db()->firstOrCreate(['name' => SITE_NAME]); require_once path('config') . DS . 'application.php'; if (!$cli) { if (fnmatch('*/mytests', $_SERVER['REQUEST_URI'])) { self::tests(); } else { self::router(); } } }
public function load($template, $layout = '', $vars = array()) { $this->loadingTk = Timer::start('Loading template'); // Loading a new template, unset all old data $this->output = ''; $this->template = ''; $this->layout = ''; $this->vars = $vars; $this->load_template($template); if ('' != $layout) { $this->load_layout($layout); $this->output = str_replace('{{ OUTPUT_TEMPLATE }}', $this->template, $this->layout); } else { $this->output = $this->template; } return $this; }
/** * Responsible for running code that needs to be executed as wordpress is * initializing. Good place to register scripts, stylesheets, theme elements, * etc. * * @return void * @author Jared Lang **/ function __init__() { add_theme_support('menus'); add_theme_support('post-thumbnails'); add_image_size('homepage', 620); add_image_size('single-post-thumbnail', 220, 230, true); register_nav_menu('header-menu', __('Header Menu')); register_nav_menu('footer-menu', __('Footer Menu')); register_sidebar(array('name' => __('Sidebar'), 'id' => 'sidebar', 'description' => 'Sidebar found on two column page templates and search pages', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>')); /* register_sidebar(array( 'name' => __('Below the Fold - Left'), 'id' => 'bottom-left', 'description' => 'Left column on the bottom of pages, after flickr images if enabled.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', )); register_sidebar(array( 'name' => __('Below the Fold - Center'), 'id' => 'bottom-center', 'description' => 'Center column on the bottom of pages, after news if enabled.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', )); register_sidebar(array( 'name' => __('Below the Fold - Right'), 'id' => 'bottom-right', 'description' => 'Right column on the bottom of pages, after events if enabled.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', ));*/ register_sidebar(array('name' => __('Footer - Column One'), 'id' => 'bottom-one', 'description' => 'Far left column in footer on the bottom of pages.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>')); register_sidebar(array('name' => __('Footer - Column Two'), 'id' => 'bottom-two', 'description' => 'Second column from the left in footer, on the bottom of pages.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>')); register_sidebar(array('name' => __('Footer - Column Three'), 'id' => 'bottom-three', 'description' => 'Third column from the left in footer, on the bottom of pages.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>')); register_sidebar(array('name' => __('Footer - Column Four'), 'id' => 'bottom-four', 'description' => 'Far right in footer on the bottom of pages.', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>')); foreach (Config::$styles as $style) { Config::add_css($style); } foreach (Config::$scripts as $script) { Config::add_script($script); } global $timer; $timer = Timer::start(); wp_deregister_script('l10n'); set_defaults_for_options(); }
public function executeCount($query, $logComponent, $defaultGraphURI = null, $format = null) { Timer::start($logComponent . '::http::count'); $json = $this->executeQuery($query, $logComponent, $defaultGraphURI, $format); $jarr = json_decode($json, true); Timer::stop($logComponent . '::http::count'); /* "results": { "distinct": false, "ordered": true, "bindings": [ { "count": { "type": "typed-literal", "datatype": "http://www.w3.org/2001/XMLSchema#integer", "value": "30" }} ] } } */ if (isset($jarr['results']) && isset($jarr['results']['bindings'])) { $bindings = $jarr['results']['bindings']; foreach ($bindings as $one) { $count = $one['count']; return $count['value']; } } else { return 0; } }
public function runPlugin($input = array()) { $output = Plugin::$output; ///set defaults for all output $t = new Timer(); $t->start(); try { $mysql = new MySQL($input['mysqlConnection']); $rs = $mysql->runQuery($input['testQuery']); if ($row = mysql_fetch_array($rs, MYSQL_NUM)) { $output['currentStatus'] = 1; $output['returnContent'] = "All normal\n" . $row[0]; $output['measuredValue'] = $row[0]; } else { $output['currentStatus'] = 0; $output['returnContent'] = "no results were returned for the query" . $input['testQuery']; } } catch (Exception $e) { $output['currentStatus'] = 0; $output['returnContent'] = "Query {$input['testQuery']} errored:\n" . $e->getMessage(); } $output['responseTimeMs'] = (int) $t->stop(); return $output; }
/** * Sorter test method. * * @param object ISorter $sorter The sorter to test. * @param integer $n The length of array to test. * @param integer $seed A seed for the random number generator. * @param integer $m If given, data values are restricted to [0,m-1]. * (Optional). */ public static function test(ISorter $sorter, $n, $seed, $m = 0) { //printf("AbstractSorter test program.\n"); RandomNumberGenerator::setSeed($seed); $data = new BasicArray($n); for ($i = 0; $i < $n; ++$i) { $datum = intval(RandomNumberGenerator::next() * Limits::MAXINT); if ($m != 0) { $datum = $datum % $m; } $data[$i] = $datum; } $timer = new Timer(); $timer->start(); $sorter->sort($data); $timer->stop(); $datum = sprintf("%s %d %d %f", $sorter->getClass()->getName(), $n, $seed, $timer->getElapsedTime()); fprintf(STDOUT, "%s\n", $datum); fprintf(STDERR, "%s\n", $datum); for ($i = 1; $i < $n; ++$i) { if ($data[$i] < $data[$i - 1]) { printf("FAILED\n"); break; } } }
function query($sql, $verbose=false){ return new TestPostgrResult(array()); $sql = trim($sql); if($this->_postgr_link === false){ $this->_postgr_link = pg_connect("host=" . $this->host . " user="******" password="******" dbname=" . $this->database); pg_query($this->_postgr_link, "SET NAMES 'utf8'"); } if($this->_postgr_link === false){ throw new DatabaseException("could not connect to MySQL"); }; if($this->_query_cache->get($sql)){ if($verbose)echo "found in cache<br>"; $result = $this->_query_cache->get($sql); if(pg_num_rows($result)){ if($verbose) echo ": seeking to 0"; pg_result_seek($result, 0); } $ret = new PostgrResult($this->_postgr_link, $result); if($verbose) echo "<br>"; }else{ if($verbose) echo "not in cache"; $this->_query_count++; /** * this following line should be run once per connection to postgres * * i'm running it before every query. I can probably optimize this * to run once per connection, but I need to do some thorough testing... * * http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html */ pg_query($this->_postgr_link, "SET NAMES 'utf8'"); $timer = new Timer(); $timer->start(); $result = pg_query($this->_postgr_link, $sql); $ret = new PostgrResult($this->_postgr_link, $result); $timer->stop(); $time = $timer->read(); if(is_object($this->logger)){ $this->logger->log($this, ALogger::$LOW, $sql); } /** * the query is too long! oh noes! */ if($time > .1){ /** * save the query to the DB, so I can look at it later */ if(is_object($this->logger)){ $this->logger->longQuery($time, $sql); } } if(pg_last_error($this->_postgr_link)){ if($verbose) echo "postgr_error: " . pg_last_error($this->_postgr_link) . "<br>"; throw new DatabaseException(pg_last_error($this->_postgr_link)); } if(strpos($sql, "SELECT") === 0){ if($verbose) echo ": select: $sql<br><br>"; $this->_query_cache->put($sql, $result); }else{ if($verbose) echo ": not select: $sql<br>"; if($verbose) echo "clearing cache<br>"; $this->_query_cache->reset(); } } return $ret; }