def set_high_priority(logger): """ Change process priority to the highest possible. """ # use "real time" scheduler done = False sched = os.SCHED_RR prio = os.sched_get_priority_max(sched) param = os.sched_param(prio) try: os.sched_setscheduler(0, sched, param) except OSError: logger.warning("Failed to set real time process scheduler to %u, priority %u" % (sched, prio)) else: done = True logger.info("Process real time scheduler set to %u, priority %u" % (sched, prio)) if not done: # renice to highest priority target_niceness = -19 previous_niceness = os.nice(0) delta_niceness = target_niceness - previous_niceness try: new_niceness = os.nice(delta_niceness) except OSError: new_niceness = previous_niceness if new_niceness != target_niceness: logger.warning("Unable to renice process to %d, current niceness is %d" % (target_niceness, new_niceness)) else: logger.info("Process reniced from %d to %d" % (previous_niceness, new_niceness))
def set_high_priority(logger): """ Change process scheduler and priority. """ # use "real time" scheduler done = False sched = os.SCHED_RR if os.sched_getscheduler(0) == sched: # already running with RR scheduler, likely set from init system, don't touch priority done = True else: prio = (os.sched_get_priority_max(sched) - os.sched_get_priority_min(sched)) // 2 param = os.sched_param(prio) try: os.sched_setscheduler(0, sched, param) except OSError: logger.warning("Failed to set real time process scheduler to %u, priority %u" % (sched, prio)) else: done = True logger.info("Process real time scheduler set to %u, priority %u" % (sched, prio)) if not done: # renice to highest priority target_niceness = -19 previous_niceness = os.nice(0) delta_niceness = target_niceness - previous_niceness try: new_niceness = os.nice(delta_niceness) except OSError: new_niceness = previous_niceness if new_niceness != target_niceness: logger.warning("Unable to renice process to %d, current niceness is %d" % (target_niceness, new_niceness)) else: logger.info("Process reniced from %d to %d" % (previous_niceness, new_niceness))
def priority(level=0, pid=0): gc.disable() if level > 0 else gc.enable() libc.munlockall() if level == 1: policy = os.SCHED_RR elif level >= 2: policy = os.SCHED_FIFO else: policy = os.SCHED_OTHER sched_param = os.sched_param(os.sched_get_priority_max(policy)) try: os.sched_setscheduler(pid, policy, sched_param) except PermissionError: return False # try to lock memory (and we succeeded in sched already) if level >= 2: res = libc.mlockall(MCL_CURRENT | MCL_FUTURE) if res != 0: libc.munlockall() return True
def define_priority(): """.""" # sched = _os.SCHED_FIFO sched = _os.SCHED_RR prio = _os.sched_get_priority_max(sched) param = _os.sched_param(prio) try: _os.sched_setscheduler(0, sched, param) print('High priority set!') except PermissionError: print('Could not set priority')
def __init__(self, ag_protocol: AbstractTransport, magnetometer_protocol: AbstractTransport, high_priority: bool = False): self.ag = ag_protocol self.mag = magnetometer_protocol # Needs to be a high priority process or it'll drop samples # when other processes are under heavy load. if high_priority: priority = os.sched_get_priority_max(os.SCHED_FIFO) param = os.sched_param(priority) os.sched_setscheduler(0, os.SCHED_FIFO, param)
def set_high_priority(logger): """ Change process scheduler and priority. """ # use "real time" scheduler done = False sched = os.SCHED_RR if os.sched_getscheduler(0) == sched: # already running with RR scheduler, likely set from init system, don't touch priority done = True else: prio = (os.sched_get_priority_max(sched) - os.sched_get_priority_min(sched)) // 2 param = os.sched_param(prio) try: os.sched_setscheduler(0, sched, param) except OSError: logger.warning( "Failed to set real time process scheduler to %u, priority %u" % (sched, prio)) else: done = True logger.info("Process real time scheduler set to %u, priority %u" % (sched, prio)) if not done: # renice to highest priority target_niceness = -19 previous_niceness = os.nice(0) delta_niceness = target_niceness - previous_niceness try: new_niceness = os.nice(delta_niceness) except OSError: new_niceness = previous_niceness if new_niceness != target_niceness: logger.warning( "Unable to renice process to %d, current niceness is %d" % (target_niceness, new_niceness)) else: logger.info("Process reniced from %d to %d" % (previous_niceness, new_niceness))
def wrapper(*args, **kwargs): did_sched = False try: pri = os.sched_get_priority_max(os.SCHED_RR) sched = os.sched_param(pri) os.sched_setscheduler(0, os.SCHED_RR, sched) did_sched = True except PermissionError as e: msg = ("Looks like you haven't set scheduling capabilities " "for your python executable, so you can't run with " "high priority. To disable this message, either consider " "running `sudo setcap cap_sys_nice+ep /path/to/python3` or " "comment out the `@hi_priority` decorator above the " "rf_send function, since it's not working anyway, or just " "increase the logging threadshold higher than `info`. NB: " "`setcap` will *not* work on symlinks, you must provide " "the path to the actual python3 executable.") logger.info(e) logger.info(msg) func(*args, **kwargs) if did_sched: os.sched_yield()
def get_priority_max(self, sched): return os.sched_get_priority_max(sched)
# gc.disable() if os.name != "nt": print("Making highest priority, os.SCHED_RR") try: pid = os.getpid() niceValue = os.nice(-20) sys.setswitchinterval(0.5) print("sys.getswitchinterval", sys.getswitchinterval()) os.sched_setaffinity(pid, [(os.cpu_count() or 1) - 1]) os.sched_setscheduler(pid, os.SCHED_RR, os.sched_param(1)) print("sched_getscheduler", os.sched_getscheduler(pid)) print("sched_getparam", os.sched_getparam(pid)) print("sched_getaffinity", os.sched_getaffinity(pid)) print("sched_getprioritymax", os.sched_get_priority_max(0)) print("sched_getprioritymin", os.sched_get_priority_min(0)) print("sched_rr_getinterval", os.sched_rr_get_interval(pid)) print("nice", os.nice(0)) except PermissionError: print("run as root to make top OS priority for more accurate results.") else: print("lol windows good luck") for i in range(5): print("pass", i + 1) for j in range(1_000_000): if sum(j for j in range(10)) < 0: raise RuntimeError
def test_priority_in_boundaries(self): self.assertGreaterEqual(config.PROCESS_PRIORITY_REAL, os.sched_get_priority_min(os.SCHED_RR)) self.assertLessEqual(config.PROCESS_PRIORITY_REAL, os.sched_get_priority_max(os.SCHED_RR))
#! /usr/bin/python3 import os print ("FIFO : {} <= prio <= {}".format( os.sched_get_priority_min(os.SCHED_FIFO), os.sched_get_priority_max(os.SCHED_FIFO))) print ("RR : {} <= prio <= {}".format( os.sched_get_priority_min(os.SCHED_RR), os.sched_get_priority_max(os.SCHED_RR))) print ("OTHER: {} <= prio <= {}".format( os.sched_get_priority_min(os.SCHED_OTHER), os.sched_get_priority_max(os.SCHED_OTHER)))
from pendulum import * import os param = os.sched_param(os.sched_get_priority_max(os.SCHED_FIFO)) os.sched_setscheduler(0, os.SCHED_FIFO, param) bus = can.interface.Bus(bustype='socketcan', channel='can0', bitrate=1000000) motor = Actuator(0x141, bus) pendulum = Pendulum(0.126, 0.15) N = 4000 proc_time = np.zeros(N) X_ar = np.zeros((4, N)) state = motor.get_state() for i in range(N): X_des = ident_traj(np.array([state.time])) X = state.X u = pendulum.control(X_des, X) proc_time[i] = state.time X_ar[0, i] = state.time X_ar[1:3, i] = state.X.reshape((1, 2)) X_ar[3, i] = state.current state = motor.send_current(u) motor.send_current(0) print(state.time) np.savetxt("data_dyn.csv", np.transpose(X_ar), delimiter=',')
def run(self): logger = self.logger ''' # wtf. python's built in os.sched_setscheduler() just does not do SCHED_FIFO any more. even # with caps set, it still returns EPERM # turns out systemd's logind puts ssh users into a cgroup that can't do RT. # move your shell to the default cpu group with: # cgclassify -g cpu:/ $$ # then you can do things like the following. # do it with C instead c = ctypes.cdll.LoadLibrary('libc.so.6') SCHED_FIFO = 1 class _SchedParams(ctypes.Structure): _fields_ = [('sched_priority', ctypes.c_int)] schedParams = _SchedParams() schedParams.sched_priority = c.sched_get_priority_max(SCHED_FIFO) err = c.sched_setscheduler(0, SCHED_FIFO, ctypes.byref(schedParams)) if err: logger.critical('couldn\'t set scheduler priority: {}'.format(err)) ''' sp_max = os.sched_get_priority_max(os.SCHED_FIFO) # see 'man sched_setscheduler', sp = os.sched_param(99) # range 1 (low) - 99 (high), for FIFO in linux try: os.sched_setscheduler(0, os.SCHED_FIFO, sp) # FIFO or RR are real-time policies (linux) except PermissionError: logger.critical('prctl.capbset.sys_nice ={}'.format(prctl.capbset.sys_nice)) logger.critical('prctl.capbset.net_admin ={}'.format(prctl.capbset.net_admin)) logger.critical('prctl.capbset.net_raw ={}'.format(prctl.capbset.net_raw)) logger.critical('[1;31mPermission denied[0m. Does the python binary have cap_net_raw,cap_sys_nice,cap_net_admin=eip? or do you need to run this? cgclassify -g cpu:/ $$') quit #os.setpriority(os.PRIO_PROCESS, 0, -20) in_process = False session_stats=(0,0,0) #print('attach debugger within 30 seconds now') #time.sleep(30) while not self._shutdown.is_set(): if not (self.online and self.handle): self.start_handle() continue try: rval = self.handle.next() if rval: pkthdr, packet = rval rval = 1 caplen = pkthdr.getcaplen() hlen = pkthdr.getlen() timestamp = pkthdr.getts() timestamp = timestamp[0] + timestamp[1]/1000000 else: rval = 0 except: t,v,tb = sys.exc_info() self.logger.warning('some bad foo, restarting capture: {}'.format(v)) self.online = False time.sleep(10) # timeout expired if rval == 0: # this should go in the EventManger # every 1 second, check the events queue for stalled or 2MSL # that need to be pushed to the API #self.events_scan() continue if not rval == 1: logger.critical('unexpected rval: {}'.format(rval)) self.lastevent = datetime.datetime.utcnow() ev = self.process_packet(hlen, caplen, timestamp, packet) if ev: # TCP conversation is finished logger.info('event {} ready for payload processing; hand off to queue'.format(ev.uuid)) # tell event manager to pop its cherry self.eventmanager.pending.set() '''
#! /usr/bin/python3 # ------------------------------------------------------------------ # exemple-get-priority-min-max.py # Fichier d'exemple du livre "Developpement Systeme sous Linux" # (C) 2015-2019 - Christophe BLAESS <*****@*****.**> # https://www.blaess.fr/christophe/ # ------------------------------------------------------------------ import os print("FIFO : {} <= prio <= {}".format( os.sched_get_priority_min(os.SCHED_FIFO), os.sched_get_priority_max(os.SCHED_FIFO))) print("RR : {} <= prio <= {}".format(os.sched_get_priority_min(os.SCHED_RR), os.sched_get_priority_max(os.SCHED_RR))) print("OTHER: {} <= prio <= {}".format( os.sched_get_priority_min(os.SCHED_OTHER), os.sched_get_priority_max(os.SCHED_OTHER)))
ret, frame = cap.read() roll_vector = bno.read_euler()[1] frame = rotate_image(frame, roll_vector) cv2.imshow('Camera 0', frame) if cv2.waitKey(1) == 27: cap.release() cv2.destroyAllWindows(); break if __name__ == "__main__": # Make process realtime niceness = os.nice(0) os.nice(-20-niceness) print("Nice level of {} selected".format(os.nice(0))) max_pri = os.sched_get_priority_max(os.SCHED_RR) sched_param = os.sched_param(max_pri) os.sched_setscheduler(0, os.SCHED_RR, sched_param) # Parser for command-line arguments parser = argp.ArgumentParser(description="Take a video and rotate it along the roll Euler vector.") parser.add_argument('--seconds', metavar='s', type=int, default=5, help="How many seconds to record") parser.add_argument('--live', metavar='l', type=str2bool, nargs='?', const=True, default=False, help="Should the recording be displayed as a window?") args = parser.parse_args() start = timer() if args.live: display_recording() else: