< main menu

Precision – depending on available resource in PHP

December 25, 2013 -
running out of time

Done is better then perfect – sometimes even true in the PHP environment, e.g.: dealing with statistics when a raw calculation can be enough or just not as painful as eating all of the memory.


In a recent past I facing a problem, I had to create a function which print the sellers (shop in shop) based on theirs belonging categories. The way of the calculation was quite heavy and we have to respect our memory and generation time restrictions.
I wrote a method which check the available time and memory frame. Now the calculation process can be as precise as possible – depends on resources.

    /**
     * determines whether the code overused the given resources
     * @param float $timeLimit time limit in seconds or microtime
     * @param int $memoryLimit memory limit in bytes
     * @return bool returns true if the system has more resources and false if not
     */
    function doWeHaveMoreResource($timeLimit, $memoryLimit) {
        static $startTime = 0;
        static $startMemory = 0;
        static $phpMemoryLimit = 0;
        if ($startTime === 0) {
            $startTime = microtime(true);
            $startMemory = memory_get_usage();
            $phpMemoryLimit = ini_get('memory_limit');
            if (preg_match('/^(\d+)(.)$/', $phpMemoryLimit, $matches)) {
                if ($matches[2] == 'M') {
                    $phpMemoryLimit = $matches[1] * 1024 * 1024; // nnnM -> nnn MB
                } else if ($matches[2] == 'K') {
                    $phpMemoryLimit = $matches[1] * 1024; // nnnK -> nnn KB
                }
            }
        }
        if (($startTime + $timeLimit) < microtime(true)) {
            mylog("no, we have no more time");
            return false;
        }
        if (($startMemory + $memoryLimit) < memory_get_usage()) {
            mylog("no, we have no more memory");
            return false;
        }
        if ($phpMemoryLimit < (memory_get_usage() / 0.9)) {
            mylog("no, we are close to php memory limit");
            return false;
        }
        return true;
    }
Tags: ,
balbu web solutions