作者:baiol
项目:RasterizeBundl
/**
* @param $url
* @param array $arguments
* @param string $uniqueId
*
* @throws \Exception
*
* @return string
*/
public function rasterizeUrl($url, $arguments = array(), $uniqueId = "")
{
if ($uniqueId === "") {
$uniqueId = uniqid("rasterize-");
}
if ($this->stopwatch instanceof Stopwatch) {
if ($this->stopwatch->isStarted($uniqueId)) {
$this->stopwatch->lap($uniqueId);
} else {
$this->stopwatch->start($uniqueId);
}
}
$process = $this->configHelper->buildProcess($url, $uniqueId, $arguments);
$exitCode = $process->run();
if ($exitCode != 0) {
throw new \Exception(sprintf("Rasterize script failed.\nCommandLine: %s\nExitCode: %d\nErrorOutput: %s", $process->getCommandLine(), $process->getExitCode(), $process->getErrorOutput()));
}
if ($this->stopwatch instanceof Stopwatch) {
$this->stopwatch->stop($uniqueId);
}
$output = $this->configHelper->getOutputFilePath($uniqueId);
$content = file_get_contents($output);
unlink($output);
return $content;
}
作者:cleverag
项目:php-orchestrato
/**
* @param CleverAge\Orchestrator\Events\ServiceEvent $event
* @return Symfony\Component\Stopwatch\StopwatchEvent
*/
protected function startProfiling(ServiceEvent $event)
{
if ($this->stopwatch instanceof Stopwatch) {
$this->profiles[$event->getService()->getName()][$this->counter] = array('method' => $event->getRequestMethod(), 'parameters' => print_r($event->getRequestParameters(), true), 'results' => null, 'duration' => null, 'result_count' => 0);
return $this->stopwatch->start($event->getService()->getName() . '_' . $this->counter);
}
}
作者:mattvaad
项目:hri
public function load(ObjectManager $manager)
{
$stopwatch = new Stopwatch();
$stopwatch->start('dummyValidationGeneration');
// Populate dummy forms
$this->addDummyValidations();
foreach ($this->getValidations() as $key => $humanResourceValidation) {
$validation = new Validation();
$validation->setName($humanResourceValidation['name']);
$validation->setDescription($humanResourceValidation['description']);
$validation->setOperator($humanResourceValidation['operator']);
$validation->setLeftExpression($humanResourceValidation['leftExpression']);
$validation->setRightExpression($humanResourceValidation['rightExpression']);
$this->addReference(strtolower(str_replace(' ', '', $humanResourceValidation['name'])) . '-form', $validation);
$manager->persist($validation);
}
$manager->flush();
/*
* Check Clock for time spent
*/
$dummyValidationGenerationTime = $stopwatch->stop('dummyValidationGeneration');
$duration = $dummyValidationGenerationTime->getDuration() / 1000;
unset($stopwatch);
if ($duration < 60) {
$durationMessage = round($duration, 2) . ' seconds';
} elseif ($duration >= 60 && $duration < 3600) {
$durationMessage = round($duration / 60, 2) . ' minutes';
} elseif ($duration >= 3600 && $duration < 216000) {
$durationMessage = round($duration / 3600, 2) . ' hours';
} else {
$durationMessage = round($duration / 86400, 2) . ' hours';
}
//echo "Dummy Validations generation complete in ". $durationMessage .".\n\n";
}
作者:sroz
项目:toleranc
function it_uses_the_span_name_when_only_one_is_traced(Tracer $decoratedTracer, Stopwatch $stopwatch)
{
$spans = [new Span(Identifier::fromString('1234'), 'name', Identifier::fromString('1234'))];
$stopwatch->start('trace (name)')->shouldBeCalled();
$stopwatch->stop('trace (name)')->shouldBeCalled();
$this->trace($spans);
}
作者:mattvaad
项目:hri
/**
* {@inheritDoc}
* @see Doctrine\Common\DataFixtures.FixtureInterface::load()
*/
public function load(ObjectManager $manager)
{
$stopwatch = new Stopwatch();
$stopwatch->start('dummyDataTypesGeneration');
// Load Public Data
$dataTypeNames = array('String', 'Integer', 'Double', 'Date', 'Telephone', 'Email');
foreach ($dataTypeNames as $key => $dataTypeName) {
$dataType = new DataType();
$dataType->setName($dataTypeName);
$manager->persist($dataType);
$this->addReference(strtolower($dataTypeName) . '-datatype', $dataType);
}
$manager->flush();
/*
* Check Clock for time spent
*/
$dummyDataTypesGenerationTime = $stopwatch->stop('dummyDataTypesGeneration');
$duration = $dummyDataTypesGenerationTime->getDuration() / 1000;
unset($stopwatch);
if ($duration < 60) {
$durationMessage = round($duration, 2) . ' seconds';
} elseif ($duration >= 60 && $duration < 3600) {
$durationMessage = round($duration / 60, 2) . ' minutes';
} elseif ($duration >= 3600 && $duration < 216000) {
$durationMessage = round($duration / 3600, 2) . ' hours';
} else {
$durationMessage = round($duration / 86400, 2) . ' hours';
}
//echo "Dummy Data Types generation complete in ". $durationMessage .".\n\n";
}
作者:TomAda
项目:db-backu
/**
* @param InputInterface $input
* @param OutputInterface $output
*
* @return int|null
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$stopwatch = new Stopwatch();
$stopwatch->start('dbBackup');
$dumpedFiles = [];
$encryptedFiles = [];
$config = ConfigLoader::loadConfig($input->getOption('config_file') ?: 'config.yml');
$logger = LoggerFactory::getLogger($config, $output);
ErrorHandler::register($logger);
try {
// dump
foreach ($config['connections'] as $connection) {
$dumper = DatabaseDumperFactory::getDumper($connection, $logger);
$dumpedFiles = array_merge($dumpedFiles, $dumper->dump($connection['databases']));
}
// encrypt
$encrypter = FileEncrypterFactory::getEncrypter($config['encryption'], $logger);
$encryptedFiles = $encrypter->encrypt($dumpedFiles);
// store
// todo: add factory?
$store = new S3StorageAdapter($config['s3'], $logger);
$store->store($encryptedFiles);
// rotate
//$rotator = new BackupRotator($config['rotation']);
//$rotator->rotate($store);
} catch (\Exception $e) {
$logger->error('Unhandled exception: ' . $e->getMessage());
}
// cleanup
FileWiper::wipe($dumpedFiles, $logger);
FileWiper::wipe($encryptedFiles, $logger);
$logger->notice('Completed backup in ' . (string) $stopwatch->stop('dbBackup'));
// todo: return non-zero if any errors
return 0;
}
作者:csanque
项目:fakery-generato
/**
* @dataProvider providerDump
*/
public function testDump($config, $zipped, $configFormat, $expectedOutput, $expectedFiles, $expectedFilesInZip)
{
$output = new BufferedOutput();
$progress = new ProgressHelper();
$outputDir = static::$cacheDir . '/dump';
$stopwatch = new Stopwatch();
$stopwatch->openSection();
$this->dumpManager->setStopwatch($stopwatch);
$this->dumpManager->setOutput($output);
$this->dumpManager->setProgress($progress);
$files = $this->dumpManager->dump($config, $outputDir, $zipped, $configFormat);
$stopwatch->stopSection('generate-test');
$events = $stopwatch->getSectionEvents('generate-test');
$keys = ['dumping_config', 'initializing_files', 'generating_rows', 'finalizing_files', 'compressing_files'];
foreach ($keys as $key) {
$this->assertArrayHasKey($key, $events);
}
$outputContent = $output->fetch();
$this->assertCount(count($expectedFiles), $files);
foreach ($expectedFiles as $format => $pattern) {
$this->assertRegExp('#' . $outputDir . '/' . $pattern . '#', $files[$format]);
}
if ($zipped && count($expectedFilesInZip)) {
$zippedFiles = $this->unzip($files['zip']);
sort($expectedFilesInZip);
foreach ($expectedFilesInZip as $format => $pattern) {
$this->assertRegExp('#' . $pattern . '#', $zippedFiles[$format]);
}
}
$this->assertEquals($expectedOutput, $outputContent);
}
作者:luisbrit
项目:Phraseane
protected function doExecute(InputInterface $input, OutputInterface $output)
{
$string = $input->getArgument('query');
$raw = $input->getOption('raw');
if (!$raw) {
$output->writeln(sprintf('Parsing search query: <comment>%s</comment>', $string));
$output->writeln(str_repeat('-', 20));
}
$postprocessing = !$input->getOption('no-compiler-postprocessing');
$compiler = $this->container['query_compiler'];
$stopwatch = new Stopwatch();
$stopwatch->start('parsing');
if ($input->getOption('compiler-dump')) {
$dump = $compiler->dump($string, $postprocessing);
} else {
$query = $compiler->parse($string, $postprocessing);
$dump = $query->dump();
}
$event = $stopwatch->stop('parsing');
if (!$raw) {
$output->writeln($dump);
$output->writeln(str_repeat('-', 20));
$output->writeln(sprintf("Took %sms", $event->getDuration()));
} else {
$output->write($dump);
}
}
作者:netzmach
项目:contao-dom-manipulato
function it_stops(Stopwatch $stopwatch, StopwatchEvent $event)
{
$stopwatch->getEvent('dom_manipulator_rules')->shouldBeCalled()->willReturn($event);
$stopwatch->stop('dom_manipulator')->shouldBeCalled()->willReturn($event);
$stopwatch->stop('dom_manipulator_manipulation')->shouldBeCalled()->willReturn($event);
$this->stop();
}
作者:mattvaad
项目:hri
/**
* {@inheritDoc}
* @see Doctrine\Common\DataFixtures.FixtureInterface::load()
*/
public function load(ObjectManager $manager)
{
$stopwatch = new Stopwatch();
$stopwatch->start('dummyInputTypesGeneration');
$this->addDummyInputTypes();
// Load Public Data
$inputTypeNames = array('Text', 'Password', 'Radio', 'Checkbox', 'TextArea', 'Date', 'Select');
foreach ($this->inputTypes as $inputTypeKey => $humanResourceInputType) {
$inputType = new InputType();
$inputType->setName($humanResourceInputType['name']);
$inputType->setDescription($humanResourceInputType['description']);
$inputType->setHtmltag($humanResourceInputType['htmltag']);
$manager->persist($inputType);
$this->addReference(strtolower($humanResourceInputType['name']) . '-inputtype', $inputType);
}
$manager->flush();
/*
* Check Clock for time spent
*/
$dummyInputTypesGenerationTime = $stopwatch->stop('dummyInputTypesGeneration');
$duration = $dummyInputTypesGenerationTime->getDuration() / 1000;
unset($stopwatch);
if ($duration < 60) {
$durationMessage = round($duration, 2) . ' seconds';
} elseif ($duration >= 60 && $duration < 3600) {
$durationMessage = round($duration / 60, 2) . ' minutes';
} elseif ($duration >= 3600 && $duration < 216000) {
$durationMessage = round($duration / 3600, 2) . ' hours';
} else {
$durationMessage = round($duration / 86400, 2) . ' hours';
}
//echo "Dummy Input Types generation complete in ". $durationMessage .".\n\n";
}
作者:ct
项目:sench
public function build($script)
{
$dependencies = array_merge($this->dependency->getList($this->project->getPath("resources coffee {$script}.coffee")), $this->dependency->getList($this->sencha->getPath('src coffee Cti.coffee')));
$fs = new Filesystem();
$result = '';
$sourceList = array();
$stopwatch = new Stopwatch();
foreach (array_reverse($dependencies) as $coffee) {
$sourceList[] = $coffee;
$local = $this->source->getLocalPath($coffee);
$local_js = dirname($local) . DIRECTORY_SEPARATOR . basename($local, 'coffee') . 'js';
$javascript = $this->project->getPath(sprintf('build js %s', $local_js));
if (!file_exists($javascript) || filemtime($coffee) >= filemtime($javascript)) {
if ($this->debug) {
$stopwatch->start($local);
echo '- compile ' . $local;
}
$code = \CoffeeScript\Compiler::compile(file_get_contents($coffee), array('filename' => $coffee, 'bare' => true, 'header' => false));
if ($this->debug) {
$event = $stopwatch->stop($local);
echo ' (' . String::formatMilliseconds($event->getDuration()) . ' using ' . String::formatBytes($event->getMemory()) . ')' . PHP_EOL;
}
$fs->dumpFile($javascript, $code);
} else {
$code = file_get_contents($javascript);
}
$result .= $code . PHP_EOL;
}
$this->hash[$script] = $sourceList;
$this->cache->set(__CLASS__, $this->hash);
$filename = $this->project->getPath("public js {$script}.js");
$fs->dumpFile($filename, $result);
return $filename;
}
作者:narog
项目:querke
/**
* Locks and gets a file handler.
*
* @return resource The file handler.
* @throws LockingException
*/
private function getFile()
{
$init = false;
if (!file_exists($this->file)) {
$init = true;
touch($this->file);
}
$fHandler = fopen($this->file, 'r+');
$block = false;
$stopWatch = new Stopwatch();
$stopWatch->start('querker.filelock.getfile');
$locked = false;
do {
if (!flock($fHandler, LOCK_EX | LOCK_NB, $block)) {
if ($block) {
if ($stopWatch->getEvent('querker.filelock.getfile')->getDuration() <= self::MAX_WAIT_TIME * 1000) {
sleep(0.1);
} else {
throw new LockingException("Unable to get exclusive lock on file (" . $this->file . ").");
}
}
} else {
$locked = true;
}
} while (!$locked);
if ($init) {
fwrite($fHandler, serialize(new PriorityQueue()));
}
$stopWatch->stop('querker.filelock.getfile');
return $fHandler;
}
作者:visitho
项目:visitho
/**
* Execute command
*
* This method returns 0 if all executions passed. 1 otherwise.
*
* @param InputInterface $input Input
* @param OutputInterface $output Output
*
* @return integer Execution return
*
* @throws Exception
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->checkEnvironment($input, $output);
$configPath = rtrim($input->getOption('config'), '/');
$format = $input->getOption('format');
$reader = new YamlConfigurationReader();
$config = $reader->read($configPath);
if (!$config || !is_array($config)) {
$output->writeln('Configuration file not found in ' . $configPath);
return 1;
}
$output->writeln('Visithor by Marc Morera and contributors.');
$output->writeln('');
$output->writeln('Configuration read from ' . $configPath);
$output->writeln('');
$output->writeln('');
$stopwatch = new Stopwatch();
$stopwatch->start('visithor.go');
$result = $this->executeVisithor($output, $config, $format);
$event = $stopwatch->stop('visithor.go');
$output->writeln('');
$memory = round($event->getMemory() / 1048576, 2);
$output->writeln('Time: ' . $event->getDuration() . ' ms, Memory: ' . $memory . 'Mb');
$output->writeln('');
$finalMessage = 0 === $result ? '<bg=green> OK </bg=green>' : '<bg=red> FAIL </bg=red>';
$output->writeln($finalMessage);
return $result;
}
作者:janvernieuw
项目:soap-client-sf2-bridg
function it_should_stop_request(Stopwatch $stopwatch, ResponseEvent $responseEvent, RequestEvent $requestEvent, ResultInterface $result, Client $client)
{
$responseEvent->getResponse()->willReturn($result);
$responseEvent->getClient()->willReturn($client);
$stopwatch->start(Argument::type('string'))->shouldBeCalled();
$stopwatch->stop(Argument::type('string'))->shouldBeCalled();
$this->setRequest($requestEvent);
$this->setResponse($responseEvent);
}
作者:bencali
项目:Ciconi
/**
* @param $event
* @param $parameters
*
* @return mixed|void
*/
public function emit($event, $parameters)
{
self::$depth++;
$this->stopwatch->openSection();
if (isset($this->callbacks[$event])) {
if (!$this->callbacks[$event][0]) {
usort($this->callbacks[$event][1], function ($A, $B) {
if ($A[0] == $B[0]) {
return 0;
}
return $A[0] > $B[0] ? 1 : -1;
});
$this->callbacks[$event][0] = true;
}
foreach ($this->callbacks[$event][1] as $item) {
$name = $this->getCallableName($item[1]);
$this->stopwatch->start($name);
$diagnoseEvent = Event::create()->setEvent($event)->setCallback($name)->setDepth(self::$depth);
$this->events[] = $diagnoseEvent;
call_user_func_array($item[1], $this->buildParameters($parameters));
$stopwatchEvent = $this->stopwatch->stop($name);
$diagnoseEvent->setDuration($stopwatchEvent->getDuration())->setMemory($stopwatchEvent->getMemory());
}
}
$this->stopwatch->stopSection($event);
self::$depth--;
}
作者:bankir
项目:doctrine-api-bundl
/** {@inheritdoc} */
public function invoke($calls)
{
$this->stopwatch->start($this->clientName, 'rpc_call');
$collection = new TraceableResponseCollection($this->client->invoke($calls), $this->stopwatch, $this->clientName);
$this->stopwatch->stop($this->clientName);
return $collection;
}
作者:studionon
项目:webpack-bundl
/**
* @return string
*/
public function compile()
{
$this->stopwatch->start('webpack.total');
$this->stopwatch->start('webpack.prepare');
// Recompile twig templates where its needed.
$this->addSplitPoints();
$this->addResolveConfig();
// Write the webpack configuration file.
file_put_contents($this->cache_dir . DIRECTORY_SEPARATOR . 'webpack.config.js', $this->generator->getConfiguration());
$this->profiler->set('compiler.performance.prepare', $this->stopwatch->stop('webpack.prepare')->getDuration());
$this->stopwatch->start('webpack.compiler');
$this->process->run();
$output = $this->process->getOutput() . $this->process->getErrorOutput();
$this->profiler->set('compiler.executed', true);
$this->profiler->set('compiler.successful', strpos($output, 'Error:') === false);
$this->profiler->set('compiler.last_output', $output);
if ($this->profiler->get('compiler.successful')) {
$this->tracker->rebuild();
}
// Finally, write some logging for later use.
file_put_contents($this->cache_dir . DIRECTORY_SEPARATOR . 'webpack.compiler.log', $output);
$this->profiler->set('compiler.performance.compiler', $this->stopwatch->stop('webpack.compiler')->getDuration());
$this->profiler->set('compiler.performance.total', $this->stopwatch->stop('webpack.total')->getDuration());
return $output;
}
作者:phpextr
项目:prox
/**
* @param RequestInterface $request
* @param ResponseInterface $response
*
* @return array
*/
protected function getLogData(RequestInterface $request, ResponseInterface $response = null)
{
$time = $this->stopwatch->stop(self::STOPWATCH_EVENT)->getDuration();
$uagent = $request->getHeader('User-Agent', '-');
$uagent = $uagent[0];
$xcache = $response && $response->hasHeaderWithValue('x-cache', 'HIT') ? 'HIT' : 'MISS';
$postDumpLimit = 200;
$postData = json_encode($request->getPostParams());
if (strlen($postData) > $postDumpLimit) {
$postData = substr($postData, 0, $postDumpLimit) . '...';
}
$data = array();
$data[] = $xcache;
$data[] = bcdiv($time, 1000, 4);
// milliseconds
$data[] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
// @todo ip is always set to 127.0.0.1 due to broken request object
$data[] = $request->getMethod();
$data[] = $request->getUri();
$data[] = $response ? $response->getStatusCode() : '-';
// bytes
$data[] = $response ? $response->getLength() : '-';
// bytes
$data[] = sprintf('"%s"', $uagent);
$data[] = $postData;
return $data;
}
作者:ddrozdi
项目:dmap
/**
* {@inheritdoc}
*/
public function enter(\Twig_Profiler_Profile $profile)
{
if ($this->stopwatch && $profile->isTemplate()) {
$this->events[$profile] = $this->stopwatch->start($profile->getName(), 'template');
}
parent::enter($profile);
}
作者:nald
项目:cyberde
/**
* Logs with an arbitrary level.
*
* @param mixed $level
* @param string $message
* @param array $context
* @return null
*/
public function log($level, $message, array $context = array())
{
if (null === $this->logger) {
return;
}
$add = true;
$stackTrace = $this->getStackTrace();
if (null !== $this->stopwatch) {
$trace = debug_backtrace();
$method = $trace[3]['function'];
$watch = 'Propel Query ' . (count($this->queries) + 1);
if ('prepare' === $method) {
$this->isPrepared = true;
$this->stopwatch->start($watch, 'propel');
$add = false;
} elseif ($this->isPrepared) {
$this->isPrepared = false;
$event = $this->stopwatch->stop($watch);
}
}
// $trace[2] has no 'object' key if an exception is thrown while executing a query
if ($add && isset($event) && isset($trace[2]['object'])) {
$connection = $trace[2]['object'];
$this->queries[] = array('sql' => $message, 'connection' => $connection->getName(), 'time' => $event->getDuration() / 1000, 'memory' => $event->getMemory(), 'stackTrace' => $stackTrace);
}
$this->logger->log($level, $message, $context);
}