Sets the percentage of CPU allowed.

        :param cpu_throttling: integer
19053
def cpu_throttling(self, cpu_throttling):
        

        log.info('QEMU VM "{name}" [{id}] has set the percentage of CPU allowed to {cpu}'.format(name=self._name,
                                                                                                 id=self._id,
                                                                                                 cpu=cpu_throttling))
        self._cpu_throttling = cpu_throttling
        self._stop_cpulimit()
        if cpu_throttling:
            self._set_cpu_throttling()
1368324
def _cpu(self):
        """"""
        value = int(psutil.cpu_percent())
        set_metric("cpu", value, category=self.category)
        gauge("cpu", value)
582007
def rate_limit(limit: int, key=None):
    

    def decorator(func):
        setattr(func, 'throttling_rate_limit', limit)
        if key:
            setattr(func, 'throttling_key', key)
        return func

    return decorator
364448
def set_output_data_rate(self, output_data_rate):
        
        # self.standby()
        register = self.MMA8452Q_Register['CTRL_REG1']
        self.board.i2c_read_request(self.address, register, 1,
                                    Constants.I2C_READ | Constants.I2C_END_TX_MASK,
                                    self.data_val, Constants.CB_TYPE_DIRECT)


        control_reg = self.wait_for_read_result()
        control_reg = control_reg[self.data_start]

        control_reg &= 0xC7  # Mask out data rate bits
        control_reg |= (output_data_rate << 3)
        self.board.i2c_write_request(self.address, [register, control_reg])
198009
def _stop_cpulimit(self):
        

        if self._cpulimit_process and self._cpulimit_process.returncode is None:
            self._cpulimit_process.kill()
            try:
                self._process.wait(3)
            except subprocess.TimeoutExpired:
                log.error("Could not kill cpulimit process {}".format(self._cpulimit_process.pid))
30620
public function determineCPUPercentage()
     {
         // Time?
         if (!empty($this->settings['timer'])) {
             $t = new Timer('Determining CPU usage');
         }

         $iterations = 2;

         // Probably only inline function here. Only used once so it makes sense.

         for ($i = 0; $i < $iterations; ++$i) {
             $contents = Common::getContents('/proc/stat', false);

             // Yay we can't read it so we won't sleep below!
             if (!$contents) {
                 continue;
             }

             // Overall system CPU usage
             if (preg_match('/^cpu\s+(.+)/', $contents, $m)) {
                 $this->cpu_percent['overall'] = $this->cpuPercent('overall', $m[1]);
             }

             // CPU usage per CPU
             if (preg_match_all('/^cpu(\d+)\s+(.+)/m', $contents, $cpus, PREG_SET_ORDER)) {
                 foreach ($cpus as $cpu) {
                     $this->cpu_percent['cpus'][$cpu[1]] = $this->cpuPercent('c'.$cpu[1], $cpu[2]);
                 }
             }

             // Following two lines make me want to puke as they go against everything linfo stands for
             // this functionality will always be disabled by default
             // Sleep *between* iterations and only if we're doing at least two of them
             if ($iterations > 1 && $i != $iterations - 1) {
                 sleep(1);
             }
         }
     }
946580
def rate_limited(max_per_second):
    
    min_interval = 1.0 / float(max_per_second)

    def decorate(func):
        last_time_called = [0.0]
        rate_lock = threading.Lock()  # To support multi-threading

        def rate_limited_function(*args, **kargs):
            try:
                rate_lock.acquire(True)
                elapsed = time.clock() - last_time_called[0]
                wait_time_remaining = min_interval - elapsed
                if wait_time_remaining > 0:
                    time.sleep(wait_time_remaining)
                last_time_called[0] = time.clock()
            finally:
                rate_lock.release()
            return func(*args, **kargs)
        return rate_limited_function
    return decorate
1103807
def set_idlemax(self, idlemax):
        

        is_running = yield from self.is_running()
        if is_running:  # router is running
            yield from self._hypervisor.send('vm set_idle_max "{name}" 0 {idlemax}'.format(name=self._name, idlemax=idlemax))

        log.info('Router "{name}" [{id}]: idlemax updated from {old_idlemax} to {new_idlemax}'.format(name=self._name,
                                                                                                      id=self._id,
                                                                                                      old_idlemax=self._idlemax,
                                                                                                      new_idlemax=idlemax))

        self._idlemax = idlemax
683551
public void updateCpu(int cpu) {
		if (cpu < 0 || cpu > 100) {
			throw new BrokerOptionsError("Invalid CPU value (" + cpu + ")!", nodeID);
		}
		if (this.cpu != cpu) {
			this.cpu = cpu;
			cpuSeq++;
		}
		cpuWhen = System.currentTimeMillis();
	}
1028371
def rate_limit_status(self):
        
        return bind_api(
            api=self,
            path='/application/rate_limit_status.json',
            payload_type='json',
            allowed_param=['resources'],
            use_cache=False
        )
420301
function _throttle (fn, threshold) {
        var _this = this;
        if (threshold === void 0) { threshold = 250; }
        // check function
        if (typeof fn !== 'function') {
            throw new Error('You must provide a function as the first argument for throttle.');
        }
        // check threshold
        if (typeof threshold !== 'number') {
            throw new Error('You must provide a number as the second argument for throttle.');
        }
        var lastEventTimestamp = null;
        return function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i - 0] = arguments[_i];
            }
            var now = Date.now();
            if (lastEventTimestamp === null || now - lastEventTimestamp >= threshold) {
                lastEventTimestamp = now;
                fn.apply(_this, args);
            }
        };
    }
870686
def SetPercentage(self, percent, total):
        """"""
        self.percentageView = percent
        self.total = total
1111437
def Cpu():
    
    cpu = 'Unknown'

    try:
        cpu = str(multiprocessing.cpu_count())
    except Exception as e:  # pragma: no cover
        logger.error("Can't access CPU count' " + str(e))
    return cpu
34985
def _available_cpu_count():
    
    try:
        return len(os.sched_getaffinity(0))
    except AttributeError:
        pass
    import re
    try:
        with open('/proc/self/status') as f:
            status = f.read()
        m = re.search(r'(?m)^Cpus_allowed:\s*(.*)$', status)
        if m:
            res = bin(int(m.group(1).replace(',', ''), 16)).count('1')
            if res > 0:
                return res
    except IOError:
        pass
    try:
        import multiprocessing
        return multiprocessing.cpu_count()
    except (ImportError, NotImplementedError):
        return 1
1290522
def is_throttled(e):
    
    return True if (hasattr(e, 'response') and
                    e.response is not None and
                    'Error' in e.response and
                    e.response['Error']['Code'] in ['Throttling', 'RequestLimitExceeded', 'ThrottlingException']) else \
        False
828019
def cpu():
    '''
    
    '''

    # Test data
    max_primes = [500, 1000, 2500, 5000]

    # Initializing the test variables
    test_command = 'sysbench --test=cpu --cpu-max-prime={0} run'
    result = None
    ret_val = {}

    # Test beings!
    for primes in max_primes:
        key = 'Prime numbers limit: {0}'.format(primes)
        run_command = test_command.format(primes)
        result = __salt__['cmd.run'](run_command)
        ret_val[key] = _parser(result)

    return ret_val
771869
def __set_rate_type(self, value):
        '''
        
        '''
        if value not in [RATE_TYPE_FIXED, RATE_TYPE_PERCENTAGE]:
            raise ValueError("Invalid rate type.")

        self.__rate_type = value