#!/usr/bin/php
<?php

$stats = array();

while ( true ) {
    exec('ps -eo %cpu,user', $processes);
    array_shift($processes); // Remove first line
    foreach($processes as $process) {
        $process = preg_replace('!\s+!', ' ', $process );
        list($cpu, $user) = split( ' ', trim( $process ) );
        $cpu = preg_replace( '/[^[0-9]]/', '', $cpu );
        if ( ctype_digit( $user ) ) {
          $info = posix_getpwuid( $user );
          $user = $info['name'];
        }
        if ( !isset($stats[$user]) ) $stats[$user] = 0;
        $stats[$user] += (float) $cpu/10;
    }
    natsort( $stats );
    $stats = array_reverse( $stats, true );
    // Clear screen
    print chr(27) . "[2J" . chr(27) . "[;H";

    $i = 0;
    foreach ( $stats as $user => $cpu ) {
      print ++$i . ": {$user} {$cpu}" . PHP_EOL;
      if ( $i > 19 ) break;
    }
    print PHP_EOL;
    sleep(1);
}

?>