import sre
import time

prev_idle = []
prev_time = 0

def busy_time_percentage():
    '''
    Returns a list of the busy time of all cpus as a percentage. 
    On the 1st call the list returned will be empty
    '''
    global prev_idle
    global prev_time
    idle = []
    stat_file = file('/proc/stat')
    lines = stat_file.readlines()
    busy_percentages = []
    for l in lines:
        #the r in r'somestring' specifies raw string - means that you don't have to escape a backslash
        pattern = sre.compile(r'cpu[0-9]+')
        match = pattern.search(l)
        if match:
            start, end = match.span()
            cpu_name = l[start:end]
            #idle time is the 5th number in the list (index 4) in 100ths of a second
            pattern = sre.compile(r'\d+')
            matches = pattern.findall(l)
            idle.append(long(matches[4]))

    if prev_idle != []:
        idle_diff = map(lambda x,y:x-y, idle, prev_idle)
        t = time.time()
        d = t - prev_time
        #Convert to 100ths of a second since /proc/stat is in 100ths of a second
        d *= 100.0

        #cap the idle time deltas to d - idle time should at most be d. The
        #only reason we have slight inaccuracies where the idle diff is
        #sometimes greater than d is probably because of rounding error in the
        #data read from /proc/stat or some other sampling error.
        idle_diff = map(lambda x : min(x, d), idle_diff)

        #compute the percentage of time spent busy.
        busy_percentages = [(d - x)/d * 100.0 for x in idle_diff]
        prev_time = t
    else:
        prev_time = time.time()

    prev_idle = idle
    return busy_percentages


def cpu_count():
    '''
    Return the number of cpus on the machine
    '''
    cpuinfo_file = file('/proc/cpuinfo')
    lines = cpuinfo_file.readlines()
    cpu_count = 0
    for l in lines:
        pattern = sre.compile(r'processor')
        match = pattern.search(l)
        if match:
            cpu_count += 1
    return cpu_count

