php - 在 PHP 中迭代日期时的效率

标签 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...
    }
}

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

如有任何帮助,我们将不胜感激!

最佳答案

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

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

关于php - 在 PHP 中迭代日期时的效率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11298883/

相关文章:

php - 使用 mysqli 更新表

php - 修改从 PDO 和 PHP 生成的 json

php - Apache 使用 http 和 https 设置多个域

ruby-on-rails - Rails 4, order in has_many :through. 它什么都不做

PHP MongoDB 身份验证失败

php - 计算服务器php的正常运行时间

c++ - 使用我的代码加速序列的生成

javascript - 用于检查 JS 数组中重复值的更快代码

c++ - 在 C/C++ 中进行大文本关键字搜索的最快方法

r - R中帕累托前沿的快速计算