<?php

/**
 * this class is used for CPU usage calculation
 * you can use this class to profile your application's CPU usage
 * returns both computation time and system calls time
 *
 * Class Core_Timer_CpuTimer
 */
class Core_Timer_CpuTimer
{

    /**
     * @var array
     */
    protected $timeStart;

    /**
     * @var array
     */
    protected $timeEnd;

    public function start()
    {
        $this->timeStart = getrusage();
    }

    public function stop()
    {
        $this->timeEnd = getrusage();
    }

    private function runTime($index)
    {
        $rue = $this->timeEnd;
        $rus = $this->timeStart;
        return (
            ($rue["ru_$index.tv_sec"] * 1000 + intval($rue["ru_$index.tv_usec"] / 1000))
            - ($rus["ru_$index.tv_sec"] * 1000 + intval($rus["ru_$index.tv_usec"] / 1000))
            )
            / 1000;
    }

    /**
     * @return float
     */
    public function getComputationTime()
    {
        return $this->runTime('utime');
    }

    /**
     * @return float
     */
    public function getSystemCallsTime()
    {
        return $this->runTime('stime');
    }

    /**
     * @return float
     */
    public function getTotalTime()
    {
        return $this->getComputationTime() + $this->getSystemCallsTime();
    }

    public function __toString()
    {
        return sprintf(
            "This process used %s s for its computations.\nIt spent %s s in system calls.\n",
            $this->getComputationTime(),
            $this->getSystemCallsTime()
        );
    }
} 