module NetUsage class CalcDelta def initialize(iface) @iface = iface @filePath = '/proc/net/dev' @rxCount, @txCount = readCounts end def readCounts # Read the current bytecounts from the specified file. pndFile = File.open(@filePath) pndFile.each_line(){|line| if line.index(@iface) # There may or may not be a space before the first number # depending on how many digits the number has. Hence the # more complicated split regexp. fields = line.strip.split(/[:\s]+/) rxCount = fields[1].to_i txCount = fields[9].to_i return [rxCount, txCount] end } return nil end def usage rxCount, txCount = readCounts rxUsage = rxCount - @rxCount # Handle wraparound: if rxCount < @rxCount rxUsage += 2**32 end txUsage = txCount - @txCount # Handle wraparound: if txCount < @txCount txUsage += 2**32 end @rxCount = rxCount @txCount = txCount return rxUsage + txUsage end end end