在PHP中迭代日期时的效率

时间:2012-07-02 18:08:42

标签: php performance

此应用程序的目的是以最有效的方式在商店中安排大量机器。该过程是递归的,组装时间表和测量效率。这可行,但需要几天才能运行。下面的代码块有很大的时间消耗:

foreach($machines AS $machine) {
# To begin, we analyze the schedule thus far to get this machine's existing schedule.
    $machSched = array();
    foreach($schedule AS $booking) {
        if($booking['mach']==$machine && strtotime($booking['end']) > date('U')) {
            $machSched[] = $booking;
        }
    }
    # We seek the next time the machine can be booked.  We begin by sorting its current bookings.
    aasort($machSched, 'start');
    # Now we construct the list of available times
    $lastEnd = date('U');
    $freeTimes=array();
    foreach($machSched AS $booking) {
        if(strtotime($booking['start']) > $lastEnd) $freeTimes[] = array('start' => $lastEnd, 'end' => strtotime($booking['start']));
        $lastEnd = strtotime($booking['end']);
    }
    $freeTimes[] = array('start' => $lastEnd, 'end' => strtotime('2030-12-31'));
    # Now we go through each available timeslot to see what we can book.
    foreach($freeTimes AS $slot) {
                   // Scheduling stuff here...
    }
}

这个块遍历每台机器的现有预定时间,对它们进行排序,并创建一个“空闲槽”阵列(现有预定项目之间的时间。我已经优化并优化了该程序,但我似乎无法看到想出一个更好的方法来完成这一小部分。注意aasort是一个函数,用于通过关联数组中的键对关联数组进行排序。

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:2)

你做了很多时间转换(date()和strftotime()),但你可以使用$ booking ['start']和$ booking ['end']中的time()和设置来避免所有这些工作简单的数字。

ADD

当然,您可以在临时变量中缓存所有“常量”值:日期('U'),strtotime('2030-12-31'))。

答案 1 :(得分:2)

如果您知道日期的存储格式,则应该使用strptime代替strtotime。使用strtotime意味着每个调用必须独立地确定日期的格式,因此您必须在每个循环中考虑该诊断。这可能是一个显着的差异。

我的简单基准测试表明time()date('U')大约快一个数量级,而strptime()strtotime()快5倍。

相关问题