Questions and Answers :
Unix/Linux :
Limiting CPU usage under Linux: SOLUTION
Message board moderation
Author | Message |
---|---|
jombo Send message Joined: 19 Jun 05 Posts: 9 Credit: 507 RAC: 0 |
i know that this isn't the best place for news and announcements... but i can't post in forum yet because i have too few credits. because a lot of people would use boinc only if they can be able to adjust max cpu usage (for example cause they don't want to burn their laptop :) i wrote a simple program that attempts to do this job under Linux (under Windows there is ThreadMaster service, that works fine). the code is very small, uses only SIGSTOP and SIGCONT signals, and can be improved, then i post it here. to compile: gcc -o cpulimit cpulimit.c to run: cpulimit {seti pid} {cpu limit} //cpulimit.c /** * Simple program to limit the cpu usage of a process * * Author: Angelo Marletta (marlonx80@hotmail.com) */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <unistd.h> #include <sys/types.h> #include <signal.h> #include <sys/resource.h> //pid of the controlled process int pid; //SIGINT signal handler void quit(int sig) { //let the process continue if it's stopped kill(pid,SIGCONT); exit(0); } int main(int argc, char **argv) { if (argc!=3) { fprintf(stderr,"Usage: %s {pid} {max cpu percentage}\\n",argv[0]); exit(1); } pid=atoi(argv[1]); int limit=atoi(argv[2]); if (limit100) { fprintf(stderr,"limit must be in the range 0-100\\n"); exit(1); } //if possible renice this process, so it has more responsiveness if (setpriority(PRIO_PROCESS,getpid(),-20)!=0) { printf("Warning: cannot renice.\\nTo work better you should run this program as root.\\n"); } signal(SIGINT,quit); //time quantum in microseconds int period=100000; struct timespec twork,tsleep; //time to work, and time to sleep twork.tv_sec=0; twork.tv_nsec=period*limit*10; tsleep.tv_sec=0; tsleep.tv_nsec=period*(100-limit)*10; while(1) { if (kill(pid,SIGSTOP)!=0) break; nanosleep(&tsleep,NULL); if (kill(pid,SIGCONT)!=0) break; nanosleep(&twork,NULL); } perror("kill()"); exit(1); } oh....i forgot...ThreadMaster *sometimes* works! |
©2024 University of California
SETI@home and Astropulse are funded by grants from the National Science Foundation, NASA, and donations from SETI@home volunteers. AstroPulse is funded in part by the NSF through grant AST-0307956.