Verzeichnisstruktur:
composer.json
phpbench.json
src/
FormatDateBench.php
Zum Ausführen:
composer update
./vendor/bin/phpbench run src/FormatDateBench.php --report=aggregate --retry-threshold=5
composer.json
{
"name": "selfhtml/benchmark-format-date",
"description": "Benchmarks some methods to format date-strings.",
"type": "project",
"require": {
"phpbench/phpbench": "^0.16.9"
},
"autoload": {
"psr-4": {
"SelfHtml\\": "src"
}
}
}
phpbench.json
{
"bootstrap": "vendor/autoload.php"
}
src/FormatDateBench.php
<?php
namespace SelfHtml;
use \DateTime;
use \DomainException;
class FormatDateBench
{
public function provideDateStrings()
{
yield ['date' => '2019-05-07'];
}
/**
* @ParamProviders({"provideDateStrings"})
* @Warmup(5)
* @Revs({10000})
* @Iterations(5)
*/
public function benchBernd($params)
{
$date = $params['date'];
$d = explode("-", $date);
return sprintf("%02d.%02d.%02d", $d[2], $d[1], substr($d[0], 2, 4));
}
/**
* @ParamProviders({"provideDateStrings"})
* @Warmup(5)
* @Revs({10000})
* @Iterations(5)
*/
public function benchUrsus($params)
{
$date = $params['date'];
if (false === $date) {
$date = time();
}
if ('string' == gettype($date)) {
return (
substr($date, 8, 2) . '.' .
substr($date, 5, 2) . '.' .
substr($date, 2, 2)
);
} elseif ('integer' == gettype($date)) {
return date('d.m.y', $date);
} else {
trigger_error(
"function date2german: Typ für '$date' nicht implementiert.",
E_USER_NOTICE
);
return false;
}
}
/**
* @ParamProviders({"provideDateStrings"})
* @Warmup(5)
* @Revs({10000})
* @Iterations(5)
*/
public function benchDedlfix($params)
{
$input = $params['date'];
return date('d.m.y', strtotime($input));
}
/**
* @ParamProviders({"provideDateStrings"})
* @Warmup(5)
* @Revs({10000})
* @Iterations(5)
*/
public function benchRolf($params)
{
$date = $params['date'];
switch (gettype($date)) {
case 'boolean':
return date('d.m.y');
case 'integer':
return date('d.m.y', $date);
case 'string':
$yearOffs = strlen($date) == 8 ? 0 : 2;
$fmtDate = function ($s, $d, $m, $y) {
return substr($s, $d, 2).".".substr($s, $m, 2).".".substr($s, $y, 2);
};
// yy-mm-dd oder yyyy-mm-dd
if ($date[$yearOffs+2] == "-" && $date[$yearOffs+5] == "-")
return $fmtDate($date, $yearOffs+6, $yearOffs+3, $yearOffs);
// dd.mm.yy oder dd.mm.yyyy
if ($date[2] == "." && $date[5] == ".")
return $fmtDate($date, 0, 3, $yearOffs+6);
// mm/dd/yy oder mm/dd/yyyy
if ($date[2] == "/" && $date[5] == "/")
return $fmtDate($date, 3, 0, $yearOffs+6);
}
trigger_error(
"function date2german: Typ für '$date' nicht implementiert.",
E_USER_NOTICE
);
return false;
}
/**
* @ParamProviders({"provideDateStrings"})
* @Warmup(5)
* @Revs({10000})
* @Iterations(5)
*/
public function bench1UnitedPower($params)
{
$input = $params['date'];
$dateTime = DateTime::createFromFormat('Y-m-d', $input);
if ($dateTime instanceof DateTime) {
return $dateTime->format('d.m.y');
} else {
throw new DomainException("$input does not match the expected format yyyy-mm-dd.");
}
}
}