Skip to content

Instantly share code, notes, and snippets.

@KVytyagov
Created February 19, 2020 12:14
Show Gist options
  • Select an option

  • Save KVytyagov/ec7167b7ff544b12decc2a000ed425f8 to your computer and use it in GitHub Desktop.

Select an option

Save KVytyagov/ec7167b7ff544b12decc2a000ed425f8 to your computer and use it in GitHub Desktop.
<?php
$intervalsCount = 100;
$days = range(0, 100);
//shuffle($days);
$iteratedDays = array_slice($days, 0, $intervalsCount);
$intervals = [];
foreach ($iteratedDays as $days) {
$intervals[] = [
'start' => new DateTime(sprintf('-%ddays', $days + 10)),
'finish' => new DateTime(sprintf('-%ddays', $days)),
];
}
$nestedLoop = function (array $intervals) {
$overlapped = [];
$dateIntervalsCount = count($intervals);
for ($i = 0; $i < $dateIntervalsCount; $i++) {
for ($j = $i + 1; $j < $dateIntervalsCount; $j++) {
$dateTimeIntervalFrom = $intervals[$i];
$dateTimeIntervalTo = $intervals[$j];
if (
$dateTimeIntervalFrom['finish'] > $dateTimeIntervalTo['start']
&&
$dateTimeIntervalFrom['start'] < $dateTimeIntervalTo['finish']
) {
$overlapped[] = $dateTimeIntervalFrom;
$overlapped[] = $dateTimeIntervalTo;
}
}
}
return $overlapped;
};
$listSorted = function (array $intervals) {
usort($intervals, function ($a, $b) {
return $a['start'] <=> $b['start'];
});
foreach ($intervals as $idx => $interval) {
$nextInterval = $intervals[$idx+1] ?? null;
if (is_null($nextInterval)) {
continue;
}
if ($interval['finish'] > $nextInterval['start']) {
return true;
}
}
return false;
};
$results = [];
foreach ([
'nestedLoop',
'listSorted'
] as $func) {
foreach ($intervals as $interval) {
$checkedIntervals = array_merge([
[
'start' => new DateTime('tomorrow'),
'finish' => new DateTime('tomorrow +1day')
]
], $intervals);
$start = microtime(true);
$$func($checkedIntervals);
$results[$func][] = [
'time' => microtime(true) - $start
];
}
}
foreach ($results as $func => $funcResults) {
$times = array_column($funcResults, 'time');
$minTime = min($times);
$maxTime = max($times);
$avgTime = array_sum($times) / count($times);
echo "[$func] min_time: $minTime\tmax_time: $maxTime\tavg_time: $avgTime\n";
}
@KVytyagov
Copy link
Author

PHP 7.2.26-1+ubuntu18.04.1+deb.sury.org+1 (cli) (built: Dec 18 2019 14:58:00) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.26-1+ubuntu18.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
    with Xdebug v2.9.0, Copyright (c) 2002-2019, by Derick Rethans

$intervalsCount = 100;

[nestedLoop] min_time: 0.0018970966339111	max_time: 0.0050129890441895	avg_time: 0.0026297736167908
[listSorted] min_time: 0.0003819465637207	max_time: 0.00068211555480957	avg_time: 0.00042611598968506

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment