i wrote simple code display time in hh:mm:ss format. code is
#include <stdio.h> #include <time.h> int main() { time_t curtime; int h, m, s, ps; struct tm *x = localtime(&curtime); time(&curtime); ps = (*x).tm_sec; while(1) { time(&curtime); x = localtime(&curtime); h = (*x).tm_hour; m = (*x).tm_min; s = (*x).tm_sec; if(s != ps) { ps = s; printf("%02d:%02d:%02d\n", h, m, s); } } return(0); }
the code compiles , runs expected. cpu usage seems go high. when use 'top' see cpu usage, shows cpu% 96-100% (and can hear computer fan loud). how can improve code performance angle keeping code simple , short?
the reason loop hardly contain waited on (the thing printf
s, assume redirect or printf
other reason completes quickly). means program eligible run.
all other programs run on computer on other hand wait something: user input, network messages or whatever. means not eligible run of time.
what operating system because program has work do, no other process has (currently) schedule program run of time (96-100%). consequently consume cpu.
this not bad thing. if program has work should given opportunity if it's program has. it's not performance - or put in way, it's performance os give program opportunity finish fast possible (although has no idea not finish @ in case).
one thing 1 these kind of processes (ie cpu bound) lower priority. may seem counterintuitive @ first, in effect tell os assign process processing power that's not used else, mean there processing power available whenever other program has process mouse click, or keyboard input (which means wouldn't notice there's cpu heavy computation going on). oses tries automatically (linux example give precedence processes wait lot).
Comments
Post a Comment