Created
February 19, 2020 12:14
-
-
Save KVytyagov/ec7167b7ff544b12decc2a000ed425f8 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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"; | |
| } | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$intervalsCount = 100;