Thursday, December 24, 2009
Friday, December 18, 2009
A DTP ANECDOTE
It was in the odd semester of our second year of engineering, when we confronted a course known as “Design: Theory and Practice” (DTP to make it, you know, a bit crisp). The course was taught to us to implant the seeds of innovation in the young minds of the prospective engineers. The precise objective was, perhaps, to introduce the students with the know-how of Design, about its evolution, about its implementation and to accentuate the concern to consider Design as a domain having a strong confluence with that of Manufacturing.
The very first day the semester started, we were handed over the sheets explaining to us the marks distribution criteria to be followed for DTP course. Then, it looked very much even – 50% for a project that essentially required being a prototype of some unknown, non existing, innovative and original design of ours and the remaining 50% for the usual theoretical exams and quizzes. That very moment, I pondered, “Huh! At least passing this course won’t be that tough – I mean even if I don’t make my project innovative enough, any instructor would certainly be giving 20 on 50 for at least the efforts put into it. And then it is going to be a group project. Chalo, ek mein to saala apan pahle din hi paas ho
DTP started with somewhat taciturn ambience that was common among the other semester courses as well and the distinct boredom could soon be felt in the theory lectures. The theories of the evolution of Design – for example, how the modern cozy chair evolved - just somehow would not intrigue me enough. I took DTP for granted, bunked a few lectures and paid more attention to the project stuff and that too on an unprecedented stuff our group had chosen: MWM - Mechanistic Washing Machine – “Born for Innovation in Engineering.” As a matter of fact, I always made it sure to keep some cool name for everything that I made – be it Intelligent Bicycle Transmission (IBT) or Intelligent Video Monitoring System (IVMS) or that very lengthy name we, I mean my project group, kept for a video game we made as a part of Computer Graphics course - Blood Rain from The Mystique Skies (BRfTMS). For some unknown reasons, we chose this stupid name for the game. BRfTMS??? Doesn't it seem to be a name of some bizarre and sophisticated medical degree rather than an out of the box name kept by some freak for some stupid game of his! :) And then I don't care even if I was that freak!
Back to the gist - In no time, DTP opened to us to the vista that led us to myriad of complex and often nauseating lengthy equations involving matrices, trigonometric identities, and state diagrams. The toughest aspect of them all was – Visualization – of the objects and models around those three axes, one of which was dreaded the most – the invisible “zee” axis. “But then, 3D is no 3D if you can understand it!” - Our professor, I thought, taught us with this rigid notion of his. I can vividly remember everything was going smooth till 2-D translation, rotation and camera calibration but soon we entered 3D world. Lectures after lectures – all devoted to polynomials, equations and matrices involving translation, rotation, camera calibration and modeling in 3D world. DTP, to me, started seeming to be a full fledged CAD/CAM software development course, and I felt it was sort of mechanical domain biased, where we were being taught in exhaustive length the mathematical tools required for developing CAD-CAM softwares. As expected, most of us fared badly in the first Quiz. Mid sem exam was not even close to be called as an under performance – it was a total drought of positive integers on our evaluated exam sheets. Even positive real numbers less than 1, which, as a matter of fact, any mathematics novice would say - "Hey, they are infinite in quantity!" -were difficult to be seen on any of our evaluated answer sheets. Zero or 0 or zero or zerooo; this way, just the style of awarding us that naught score changed from one script to the other. I think the instructor might have been fed up writing "zero" or "0", for almost all of us, and for a change, or may be to console himself a bit, that his students can't be that idiot, started practising the various forms and styles he can award us that zero. I guess, you will agree, writing zero 75 times is boring indeed. Soonafter, worse happened. Most of us even screwed the second quiz managing the very familiar zero yet again – just the two 'designers' managed to open their DTP accounts somehow. Rest were tottering on naughts. Most of us belonged to the pool that needed some real good marks from the project and the end sem that were to follow. Frenzied ratta-fication (and I really don't care if that's not any word) of the equations involving dreaded Beizer curves, Bernstein polynomials and Envelopes was also not helping. Visualizing the models made up of complex curves meant just too much to our Medulla Oblangata - we were just so much screwed up! Hey - you see - Yaw rate angle calculation matrices were outnumbered by the yawns it caused among the people. In making a general statement here, with so much assertiveness, I may be wrong about others, but then I can’t be more correct!
Anyway, in the later-mid of the same semester, the college team planned a trip to Antaragni – IIT K cultural fest: I too happened to be a part of it. I thought a break was the need of the time to refresh my acumen. At least for some days, we can enjoy! And then we can also see some fair proportion of the other fraternity of us, that in our batch, were like two pins in a lorry full of hay stack.
But then, I was either oblivious of certain verified facts or discarded them as mere assumptions.
But then, I was either oblivious of certain verified facts or discarded them as mere assumptions.
Friends, the earthquake ends but is often followed by strong after effect tremors.
The demon dies but not the sins.
- -
- -
So, the overdose did it, Man!!
Scene: IIT
Occasion: Antaragni
One of my batch mates, 'R', (I hide here, the full name, but still I am sure am not fattu, ok, just hiding the name 'coz R is too reactive..he might just sue me you know, so just endure R) got febrile and all of a sudden caught cold and cough. Accompanied by me, he decided to go to IIT K Market complex to buy some cough syrup to cure the untimely nemesis of his. We started off in a hurry ‘coz we had to reach back to the rest of the college team in time for the events.
R – “We need to reach back, quickly!”
One of my batch mates, 'R', (I hide here, the full name, but still I am sure am not fattu, ok, just hiding the name 'coz R is too reactive..he might just sue me you know, so just endure R) got febrile and all of a sudden caught cold and cough. Accompanied by me, he decided to go to IIT K Market complex to buy some cough syrup to cure the untimely nemesis of his. We started off in a hurry ‘coz we had to reach back to the rest of the college team in time for the events.
R – “We need to reach back, quickly!”
Me – “Chill Dude! We will be there in time. Just feed yourself with a spoonful of cough syrup. Also, we have a debate event speech to deliver tomorrow – remember?”
R – “Yeah, I do”
Thereafter, it was about 5 minutes hurried walk from the temporary Hall of Residence that was allocated to our team to IIT K Market complex. It was a breezy morning, time being the late of the month of October. It was no surprise seeing R catching cold due to the seasonal change. Anyway, we reached our destination soon.
R, pointing to the medical store – “Oh ! there it is. And Thanks, its open too. Let’s go!”
I decided to follow but somehow and don't know exactly when my mind lost control over the kinetic action of my legs owing to all its attention being given to feeding my thirsty eyes with glimpse of several gorgeous chicks who were there gathered around a general store. But then, seeing a group of guys next to them, I did n’t waste much of my time in realizing the “REGRET” status which would have been on offer, had I tried my chances (of winning a date) with anyone of them. However, I surely had enough wastage of time to cause DTP over dose to play it’s part in IIT K – about 520 kilometers from the place where we practiced what was preached to us in the dreaded DTP course – in case, if we ever did. :) By the time, R had ordered the cure: the cough syrup: the antidote to his untimely nemesis. I could make this out from the roving eyes of the shopkeeper who was busy searching for the medic.
Me – “ Hmm. So you asked him?”
R – “ Yes. I have. I will take a spoonful and then…”
In midst of our conversation, we were interrupted.
Shopkeeper – “Sorry…bhaia..aapne jo maangi – woo syrup too nahin mil rahi. Kis cheez ki hai?”
I agree to the fact that I was not in one of the best hospitals of the country but in one of the best engineering institutes of it! Who cares? Benadryl should have been there. It's very common cough syrup. In fact, one of the oldest and trusted medic we resort to as soon as cough and cold influenza attack our body. Benadryl needs to be there in every medical store lest it's out of stock due to the over sale or the shopkeeper's mis management of the inventory.
Me, astonished, almost shouted – “Benadryl…nahin hai? Benadryl cough syrup hai bhai!”
Me, astonished, almost shouted – “Benadryl…nahin hai? Benadryl cough syrup hai bhai!”
R, almost coming out of a DTP coma - “Oh shit! Benadryl...sorry, Bhaia, maine Bernstein polynomial..maang liya!! huh..”
Hahaaaaaaa.That was it! R demanded the syrup named Bernstein Polynomial. That was the after effect of DTP earthquake – Imagine, the intensity - the tremors could be felt 520 kilometers away!! Those were the DTP sins chasing us all along!! The poor shopkeeper had his worst few minutes of his life searching for a syrup that never existed! Not in IIT K - not in Kanpur - not in UP - not in India - not in this Universe. I felt pity for him. He was a druggist but R assigned him the task of inventing something that never ever existed. Sorry, but R selected the poor druggist for the work of Issac Newton, expected an unexpected Archimedes' discovery out of him!! I could n’t resist. The comedy that had happened made me burst into laughter. R joined me. The shopkeeper still had no clue what had happened. How could he? I was sure he never suffered in his life from a DTP overdose.
Since then, every time I have to take BENADRYL during occasional cough and cold syndromes, this BERNSTIEIN POLYNOMIAL anecdote flashes in front of me, so vividly.. :)
Wednesday, November 25, 2009
G-i-r-l-s
Oh! We boys - how pathetic these girls make our lives! They are adorable, dominating and compelling stimuli to which we are nothing more than a feeble, weak and subservient response. :) Dudes, they drive our lives – from kindergarten to school, from school to college, from college to office – yes, everywhere I guess; and we found ourselves so mindlessly cajoled by them. We are tiny tennis balls on the TT tables and they are the stroking rackets who keep on playing shots on us and we just keep hopping from one side of court to the other.
Hey, what you gonna say about this - Comes the exam day and our mind is so full of formulae and equations. Then, comes a girl, dressed in an eye candy attire, our brains loose control over our very own eyes, she comes and sits just in front of us, or may be two seats ahead, in any case, such small distances no longer remain a potential barrier to the wild yet so beautiful and irresistible fantasies we, by the time, are already lost in. She sits, crosses her legs, makes herself comfortable and we get the most uncontrollable palpitations. The examiner hands over the question papers to us – but we see nothing but her smiling face on the papers. Alpha, Beta and Gamma get so f*g mixed up in our all memorized equations that we feel as if we have been hit by an intangible yet so devastating turbulence. She is jotting down her answers on the scripts while we are jotting down her caricature on our minds. She raises her hands to clarify an ambiguity in the paper and we get amazing Goosebumps. She queries the examiner, “Enshuldigung! … … …” Oh f*! We don’t listen to a word after that very first one – Yes, so captivated and charmed by her voice we poor fellas are – We hear festive bells ringing in our ears. Then eventually the warning bell signaling the last few remaining minutes of the exam rings and wrecks our dreamy castles. The blank answer sheet in front of us pleads to be scribbled with at least a few words – Shocked, we spent the last few minutes of the exam in scribbling some rambling thoughts on the paper – Who remembers the equations now - They are gone as if they never ever existed in our memories - huh! our complete memory system has been rebooted… … … and that was only an exam scene.
She affects our community so bad. Most of us wander around trying to buy ourselves a cool date. We boys are artful, aren’t we? Some of us, do succeed in this pursuit. Oh! And then we are so nervous on the date eve – trying to make sure everything goes well on the D – day. We have huge list to double check to avoid any last minute disappointments. And then the day arrives. The signboard at the café reads – “A lot can happen over a coffee.” We feel so confident that we are oblivious of the fact this pleasant feeling is so short-lived. Guess - why? ‘coz soon we are put in a situation where we can’t resist the feeling of touching her lips and moistening them with ours. Here, we got ourselves divided into two zones X and Y. Those of us who belong to X zone, well, we take move on our amorous advances and just kiss her!! What next – A sound – SLAPPP! "What do ya think of yourself boy? Do you think I am that indecent?” She is gone the next moment, our date is gone, and certainly, Dad’s hard earned money has been lavishly wasted on her. The Y zone of us is a bit cautious – we think, “Not Yet! First date is not the right time to Kiss.” Eventually, we end up listening – “Bye! I had a nice time with you, but I guess, can’t see boring, unromantic guys like ya anymore. And then am straight as well. Are you sure of yourself?” We are so startled to even think what to say – when she screams – “ Go away. I ain’t gay.” With this, the Y zone of us had a bonus loss to account for :) – we loose our character and dignity as well. Some serious ones of our Y zone ones might even take the words too seriously and start giving some real gravity filled thoughts over their s*x-l priorties. Phew! The date adversely affects the remaining calendar dates of our lives, and haunts us like an evil nightmare.
Hey, what you gonna say about this - Comes the exam day and our mind is so full of formulae and equations. Then, comes a girl, dressed in an eye candy attire, our brains loose control over our very own eyes, she comes and sits just in front of us, or may be two seats ahead, in any case, such small distances no longer remain a potential barrier to the wild yet so beautiful and irresistible fantasies we, by the time, are already lost in. She sits, crosses her legs, makes herself comfortable and we get the most uncontrollable palpitations. The examiner hands over the question papers to us – but we see nothing but her smiling face on the papers. Alpha, Beta and Gamma get so f*g mixed up in our all memorized equations that we feel as if we have been hit by an intangible yet so devastating turbulence. She is jotting down her answers on the scripts while we are jotting down her caricature on our minds. She raises her hands to clarify an ambiguity in the paper and we get amazing Goosebumps. She queries the examiner, “Enshuldigung! … … …” Oh f*! We don’t listen to a word after that very first one – Yes, so captivated and charmed by her voice we poor fellas are – We hear festive bells ringing in our ears. Then eventually the warning bell signaling the last few remaining minutes of the exam rings and wrecks our dreamy castles. The blank answer sheet in front of us pleads to be scribbled with at least a few words – Shocked, we spent the last few minutes of the exam in scribbling some rambling thoughts on the paper – Who remembers the equations now - They are gone as if they never ever existed in our memories - huh! our complete memory system has been rebooted… … … and that was only an exam scene.
She affects our community so bad. Most of us wander around trying to buy ourselves a cool date. We boys are artful, aren’t we? Some of us, do succeed in this pursuit. Oh! And then we are so nervous on the date eve – trying to make sure everything goes well on the D – day. We have huge list to double check to avoid any last minute disappointments. And then the day arrives. The signboard at the café reads – “A lot can happen over a coffee.” We feel so confident that we are oblivious of the fact this pleasant feeling is so short-lived. Guess - why? ‘coz soon we are put in a situation where we can’t resist the feeling of touching her lips and moistening them with ours. Here, we got ourselves divided into two zones X and Y. Those of us who belong to X zone, well, we take move on our amorous advances and just kiss her!! What next – A sound – SLAPPP! "What do ya think of yourself boy? Do you think I am that indecent?” She is gone the next moment, our date is gone, and certainly, Dad’s hard earned money has been lavishly wasted on her. The Y zone of us is a bit cautious – we think, “Not Yet! First date is not the right time to Kiss.” Eventually, we end up listening – “Bye! I had a nice time with you, but I guess, can’t see boring, unromantic guys like ya anymore. And then am straight as well. Are you sure of yourself?” We are so startled to even think what to say – when she screams – “ Go away. I ain’t gay.” With this, the Y zone of us had a bonus loss to account for :) – we loose our character and dignity as well. Some serious ones of our Y zone ones might even take the words too seriously and start giving some real gravity filled thoughts over their s*x-l priorties. Phew! The date adversely affects the remaining calendar dates of our lives, and haunts us like an evil nightmare.
Why? May I ask why are we guys so helpless? We think of her every time. At breakfast, at lunch, at dinner, in our group chats, literally every time and every place – we completely re-schedule our day plan to see her and still she would say – “You are so boring and dull - typical routine type. No fun being with ye.” You don’t see her a day and she would say – “You are so nonchalant! I mean nothing to you. I am just another option in your life. You just dont' care a damn 'bout me.” Feel the punch - If we are well dressed, she says we are playboys, if we don’t, we are not good enough to be called boys. Dude, Oh, dude what an irony is this!
Wednesday, November 18, 2009
Engineering in Practice
Hi folks..
Guess it's time to discuss some cool engineering stuff..
Let's talk about automation - Intelligent Bicycle Transmission. This novel design of Intelligent Bicycle Transmission (IBT) [(C) Arpit et al.] system provides superior efficiency to bicycle riders since it allows the rider to maintain the preferred cadence range. The system is very simple and economic yet provides an automatic gear shifting option to the cyclist at fairly accurate level. The gear manipulation in the case of a bicycle is not a simple linear progression from a lower gear to a higher gear as in a motorized vehicle, for example a car. It is instead a function of the ratio of the front gear size to the rear gear size, both of which are variable. Since years, many designs for the automated transmission have evolved; however the excessive cost and the inadequate efficiency kept the urgency and the scope of the improved designs alive. This motivated the brainstorming by a group of so called engineers who, at that point of time, were not able to think of anything better to design and fabricate!;)
I. Cadence and gearing
Bicycle’s motion is dependent on the input power being delivered by the rider in the form of pedaling. Pedaling involves rotation of a front sprocket due to pressure applied by the rider’s feet. This motion is then transmitted to the rear wheels through a chain mechanism and rear sprocket (a smaller gear attached to the rear wheels). Cycling involves different riding conditions, each having their own power requirements. For instance, while racing, more speed is desirable whereas for city commuting, comfort is preferred over speed.
II. Design of Transmission System
Based upon the theory of preferred cadence, an approach for the design of transmission system is suggested as follows: The implementation of the algorithm required fulfilling of three steps: (a) Design of two sensor devices A and B that measure the angular velocities accurately and their output is in the form of parameters that can be inputted to an electronic control unit (ECU), (b) Design of an ECU that receives the output of the sensors and controls the motion of the actuator that causes the shifting of the gear and (c) Design of an actuator that shifts the gear system as per the signals generated by the ECU. The schematic of the algorithm is shown below:
A. Sensor Devices
In the presented design, two sensors have been used. Sensor A has been used to measure cadence and Sensor B to measure angular velocity of the rear wheel. From the experimental results, it is found that a voltage range of [1.3, 1.7] V is obtained by the sensor A for the preferred cadence.
B. Electronic Control Unit
The designed ECU has two main sections: (a) Actuator Control Circuit, (b) Motor Driver Circuit.
C. Actuator
B. Electronic Control Unit
The designed ECU has two main sections: (a) Actuator Control Circuit, (b) Motor Driver Circuit.
C. Actuator
In the proposed system, a derailleur with 5 speeds or gears is used having following specifications. CAD/CAM schematic of the actual actuatuor was used in designing of IBT (drawn on Solidworks s/w) .
This is the abstract of the original work. However, disclosure of detailed designs and discussion are beyond the scope of this article due to the rights reserved with IEEE.
Labels:
Automation,
Innovation,
Intelligent Transmission,
Mechatronics
Tuesday, November 17, 2009
NEED FOR SPEED
Hi ya:).. don't ye any time came across time overshooting problems while coding some real cool stuff for programming contests like ACM ICPC? Yes, I know you certainly would have atleast once. And then nothing but a sigh - "Oh my-Oh my!! .. dhat wazz a correct code, dude; the logic I uzzed waz deadly, juss dose extra millisecondzz program took screwed it ahl! Damn! :X" And that was a very trivial example - to say the least.
In real world, while designing sophisticated real time response systems (RTRS) we do need to optimise our code again and again to make it as dazzling fast as we can. These days, Machines and Robos are almost everywhere performing numerous highly spohisticated tasks, the automotives equipped with highly intelligent DAS - Driver Assistant Systems are being launched, coolest video games with eye candy graphics and acrobatic combats are rocketing the gaming market: all having one thing in common - NEED FOR SPEED - and here, that's not the name of the famous racing game, in case you just got astrayed a bit, it is, but the commmon uproar these gadgets have - TO OPTIMIZE AGAINST TIME - JUST SPEED UP EVERYTHING!
So,right time, friends, to share some tips to optimize our programs against time. What follows is the compilation of several tricks to optimize C code. Most of them are practical and hold true even if developer has programmed the project in C++. Check them out-
Before we start Optimizing
So..Are we ready to optimize our C code..Wait..do you recall Ahmdal’s Law.This is what the law says -
Speedup = Told/Tnew
Speedup = Told/Tnew
= 1 / ( (1-fruntime) + fruntime/fspeedup)
where fruntime is the percentage of program run time used by the function 'f' and fspeedup is the factor by which we speed up this function. Now, consider a practical case. Suppose we are working on a module (say, function 'f') with the goal to optimize it against time and the whole project takes 0.250 milliseconds and we make the module run twice as fast (i.e. fspeedup=2) ; then we will get 25% speedup assuming the module(function 'f') takes 40% of the execution time of the whole project. Henceforth, the project will take 0.200 milliseconds. The overall gain is of just 50 microseconds despite doubling the speed of the module. So, optimizing has an essential pre-requisite - we must first check which modules take the most of the project's execution time. Need is to attack the code within intensive loops or that part of project which is used more frequently. Else, it's all futile spending our energy and time and we may eventually employ the coolest optimization trick from our inventory stock but that may not reflect any significant time conservation in the overall project. Checkpoint: Before we start optimizing - we need to do Profiling stuff - that is, to check the bottlenecks in our code - that is, to identify the modules we would target for optimization.
Is Optimization necessary?
The nerds have something to share - "You may write very efficient code but spend at least twice as long optimizing it." Hence, don't do it unless absolutely necessary. Necessity may arise when there is need to get a real time response as in Games, DAS gadgets, Robos etc.
Manual vs. Automatic Optimization & Algorithm Selection
The modern compilers are smart!! Thanks to the cutting edge technology - we now have really smart compilers that can do most of our work required for optimization. However, what if the requisite is to optimize something that is beyond the scope of the compiler? That's really challenging!! We need to be sure we don't baffle the optimizer by our tweaking methods. Hell lot of algorithm analysis and code understanding is required to think of changes at the algorithm level. Surely, if the code is using linear search somewhere in the module, the automatic optimizer won't implement binary search on it's own. Well, that was a very simple case. Real life projects and applications have extremely sophisticated algorithms that have a lot of interdependencies with other algorithms, and bringing about a significant change in them is not that easy; Well, even saying not that easy is an understatement.;) So good so far. So, it's like the best method of optimizing a project is to use a mixed optimization scheme - use smart and intelligent compilers to do the automatic stuff and then think something beyond the scope of the compiler. Checkpoint: The first step in Optimization is to double check that the code design is complete and then attack algorithm level changes subsequently. That's the toughest phase but at the same time, a prudently selected algorithm may conserve considerable amount of time; that cannot be obtained even after application of zillion of optimization tricks on the old algorithm.
Can a programmer outperform an optimizer?
YES
This is possible by
i - choosing a better algorithm
i - choosing a better algorithm
ii - knowing more about the definitions and uses of data items in the program eg. a programmer may know relative probabilities of branches being taken. Also An optimiser has to ensure correctness of the optimised program under all conditions hence it has to be conservative.
An optimiser may miss optimisation opportunities because of this..!
Also NO Because -
i - It takes too much time to perform some optimisations by hands viz
An optimiser may miss optimisation opportunities because of this..!
Also NO Because -
i - It takes too much time to perform some optimisations by hands viz
strength reduction, copy propagation, dead code elimination
ii - Certain machine level details are beyond the control of a programmer viz. instructions and addressing modes supported by the target machine
Tips and Tricks
Using Array Indices
If wished to set a variable to a particular character, depending upon the value of something, might do this:
switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
Alternative method is to simply use the value as an index into a character array, eg.
static char *classes="WSU";
letter = classes[queue];
switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
Alternative method is to simply use the value as an index into a character array, eg.
static char *classes="WSU";
letter = classes[queue];
Also, note that switch is always better alternative in case there are multiple if else statements. Long if...else if...else if...else if... chains require lots of jumps for cases near the end of the chain (in addition to testing each condition). If possible, convert to a switch statement, which the compiler sometimes optimizes into a table lookup with a single jump.
Integers
Use unsigned ints instead of ints if known the value will never be negative. The best declaration for an int variable in a tight loop would be:
register unsigned int var_name;
(Although it is not guaranteed that the compiler will take any notice of "register", and "unsigned" may make no difference to the processor)
Remember, integer arithmetic is much faster than floating-point arithmetic, as it can be usually be done directly by the processor, rather than relying on external FPUs or floating point maths libraries.
register unsigned int var_name;
(Although it is not guaranteed that the compiler will take any notice of "register", and "unsigned" may make no difference to the processor)
Remember, integer arithmetic is much faster than floating-point arithmetic, as it can be usually be done directly by the processor, rather than relying on external FPUs or floating point maths libraries.
Passing structures
Whenever possible, pass structures by reference (i.e. pass a pointer to the structure), otherwise the whole darn thing will be copied onto the stack and passed, which will slow things down. Functions receiving pointers to structures as arguments should declare them as pointer to const if the function is not going to alter the contents of the structure.
void print_data( const bigstruct *data_pointer)
{
...display contents of structure...
{
...display contents of structure...
}
This example informs the compiler that the function does not alter the contents (pointer to constant structure) of the external structure, and does not need to keep re-reading the contents each time they are accessed. It also ensures that the compiler will trap any accidental attempts by the code to write to the read-only structure.
This example informs the compiler that the function does not alter the contents (pointer to constant structure) of the external structure, and does not need to keep re-reading the contents each time they are accessed. It also ensures that the compiler will trap any accidental attempts by the code to write to the read-only structure.
Minimize the use of global variables
Global variables are never allocated to registers. Global variables can be changed by assigning them indirectly using a pointer, or by a function call. Hence, the compiler cannot cache the value of a global variable in a register, resulting in extra (often unnecessary) loads and stores when globals are used. We should therefore not use global variables inside critical loops.
If a function uses global variables heavily, it is beneficial to copy those global variables into local variables so that they can be assigned to registers.
If a function uses global variables heavily, it is beneficial to copy those global variables into local variables so that they can be assigned to registers.
Don't use recursion
Recursion can be very elegant and neat, but creates many more function calls which can become a large overhead.
Inline Functions
There are several advantages to using inline functions:No function call overhead. As the code is substituted directly, there is no overhead, like saving and restoring registers. Lower argument evaluation overhead. The overhead of parameter passing is generally lower, since it is not necessary to copy variables. If some of the parameters are constants, the compiler can optimize the resulting code even further. The big disadvantage of inline functions is that the code sizes increase if the function is used in many places. This can vary significantly depending on the size of the function, and the number of places where it is used.
Operations' selection
Addition is quicker than multiplication –
Do use val + val + val instead of val * 3
Do use val + val + val instead of val * 3
If necessary, make it easy on the C compiler and use bit shifts, and divisors that are a power of 2. Divisors that are a power of 2, such as 256=2^8, can be optimized into a bit shift by the C compiler.
Sometimes, such expressions can be rewritten by replacing the division by a multiplication. For example, (a / b) > c can be rewritten as a > (c * b) if it is known that b is positive and b *c fits in an integer. It will be better to use unsigned division by ensuring that one of the operands is unsigned, as this is faster than signed division.
Use shift operations >> and <<>
Avoiding Memory reads
typedef struct { int x, y, z; } Point3;
typedef struct { Point3 *pos, *direction; } Object;
void InitPos1(Object *p)
{
p->pos->x = 0;
p->pos->y = 0;
p->pos->z = 0;
}
Here better to store Object *P=p->pos;
Then P->x, P->y, P->z used.
At any cost, avoid memory reads as far as possible.
typedef struct { Point3 *pos, *direction; } Object;
void InitPos1(Object *p)
{
p->pos->x = 0;
p->pos->y = 0;
p->pos->z = 0;
}
Here better to store Object *P=p->pos;
Then P->x, P->y, P->z used.
At any cost, avoid memory reads as far as possible.
Lazy Evaluation
In if (a>10 && b=4) type of thing, make sure that the first part of the AND expression is the most likely to give a false answer (or the easiest/quickest to calculate), therefore the second part will be less likely to be executed.
Loops
Loops are a common construct in most programs; a significant amount of the execution time is often spent in loops. It is therefore worthwhile to pay attention to time-critical loops. If(a==10)
Else if(a==9)
Else if(a==8)
Else if(a==7)
Else if(a==6)
…
May be changed to
If(a<5)>5) ... etc.
Else if(a==9)
Else if(a==8)
Else if(a==7)
Else if(a==6)
…
May be changed to
If(a<5)>5) ... etc.
Loop Unrolling and Loop peeling may be automatically handled by the complier in case the optimizer is ON.
Parameters to Functions
To minimize the overhead of passing parameters to functions:
•Try to ensure that small functions take four or fewer arguments. These will not use the stack for argument passing.
•If a function needs more than four arguments, try to ensure that it does a significant amount of work, so that the cost of passing the stacked arguments is outweighed.
•Pass pointers to structures instead of passing the structure itself.
•Put related arguments in a structure, and pass a pointer to the structure to functions. This will reduce the number of parameters and increase readability.
•Try to ensure that small functions take four or fewer arguments. These will not use the stack for argument passing.
•If a function needs more than four arguments, try to ensure that it does a significant amount of work, so that the cost of passing the stacked arguments is outweighed.
•Pass pointers to structures instead of passing the structure itself.
•Put related arguments in a structure, and pass a pointer to the structure to functions. This will reduce the number of parameters and increase readability.
Fixed Point Arithmetic
When the range of values needed is sufficiently small, fixed-point arithmetic is more accurate and much faster than floating-point arithmetic.
Instruction-level-parallelism
Even though many applications still rely on single threaded execution, modern CPUs already have a significant amount of parallelism inside a single core. This means a single CPU might be simultaneously executing 4 floating point multiplies, waiting for 4 memory requests, and performing a comparison for an upcoming branch. So, must know and exploit the architecture well.
Avoid casting wherever possible
Try to avoid casting where possible. Integer and floating point instructions often operate on different registers, so a cast requires a copy. Shorter integer types (char and short) still require the use of a full-sized register, and they need to be padded to 32/64-bits and then converted back to the smaller size before storing back in memory. (However, this
cost must be weighed against the additional memory cost of a larger data type.)
cost must be weighed against the additional memory cost of a larger data type.)
Simplify mathematical equations on paper
In many equations, terms cancel out, either always or in some special cases. The compiler cannot find these simplifications, but we can. Eliminating a few expensive operations inside an inner loop can speed program more than days working on other parts.
this way, we save two divisions and even MIN macro function usage is avoided. However, this is code specific optimization and needs careful scrutiny from the optimizer's side.
Avoid redundant conditional checks
Often, many if conditions are unnecessary and can be avoided. Also, whenever possible move conditional checks outside the loops rather than keeping it inside (in case the check is independent of the index of the loop)
Club conditional checks
Two consecutive if conditional checks may be clubbed into one using logical && as this translates two JUMPS in corresponding assembly to one JUMP. Also, consecutively occuring for loop and if conditional check may be clubbed into one by removing the check within if condition and clubbing it with for loop conditional check, as follows:so, for...if... can be changed to for...only.
Monday, November 16, 2009
Sophistication vs. Simplicity

...Most of us have a blurred vision of what Life is..yeah, me too one of them. It is something too pacy and out of control - isn't it? Our frenzied madness to be at the summit, our myriad painstaking efforts to ameliorate our living and our countless obligations to our family, society, nation, globe, earth, galaxy etc. just eats away the very "Life" from us - and we remain so oblivious of the fact! We all constantly work for a better Tomorrow but when Tomorrow comes, instead of enjoying, we again think of better tomorrow! Who the hell cares to have a better Today ? Who the hell has time to pause the pace a bit and freelance, enjoy nature, and appreciate Life as wonderful blessing of the Almighty to us. We are all busy in buying ourselves the coolest sophistications money and technology can provide us with...Surpisingly, so easily forgetting the inherent tranquillity simplicity has !!
Don't we admire the memories of our childhood days - the days of pure innocence - weren't they the heydays of our lives? Simplicity was the only treasure we had that time. We were so ignorant of the restlessness and complexities that the sophistications can infect us with..we were so much engrossed in chasing the butterflies brimming with the sun light on the flowers, playing numerous insane yet so cheerful simple games, visiting zoos and getting so incredibly ecstatic at the sight of lions - roaring, birds - chirping and voila! those amazing and stupid monkeys - doing those ridiculous yet so rib tickling acts to amuse us...those were the days when unknowingly, we remembered to cherish the pleasures Life bestows upon us..!! We had so less money - who the hell cared for that..? We never had these delicious pizzas, these smorgasbord of cuisines we now have but we cherished drinking the glass of hot milk that mom always got ready for us - we cherished the home made food - Oh..yes - we cherished a glass of "water" and not a bottle of "sprite" to quench our thirst!
With Time, Empathy we possessed turned to Sympathy and gradually Sympathy changed to Antipathy. "If thou fittest, thou survive." Sadly, most of us interpreted the adage, as if, asking us to be selfish - to just surpass our counterparts in each and every field by any crooked means possible - to be friendly with a person as per the demands of the hour, only to betray just an hour later. Thoughts are so confined to self thinking and selfish interests now...!! Comes the first turn in the journey of Life and we see two budding friends; the very next turn shows them becoming strangers... There is a point to make friends - We in our pursuit of achieving a class are drilling the very path we are treading on... Daily, we add a new sophistication to our inventories but obliviously take yet another step to pain and suffering - yet another artificial pleasure to make a real "Life" more unreal - isn't it..? Just ponder over, for once atleast; just focus your roving eyes on the vista that shows you glimpses of your past - Give it a thought... Life is meant to be enjoyed with your family and friends. Don't waste yours, chasing materialistic and lifeless sophistications - Oh Man, your stay here is temporary - ENJOY IT BEFORE IT'S TOO LATE!
Don't we admire the memories of our childhood days - the days of pure innocence - weren't they the heydays of our lives? Simplicity was the only treasure we had that time. We were so ignorant of the restlessness and complexities that the sophistications can infect us with..we were so much engrossed in chasing the butterflies brimming with the sun light on the flowers, playing numerous insane yet so cheerful simple games, visiting zoos and getting so incredibly ecstatic at the sight of lions - roaring, birds - chirping and voila! those amazing and stupid monkeys - doing those ridiculous yet so rib tickling acts to amuse us...those were the days when unknowingly, we remembered to cherish the pleasures Life bestows upon us..!! We had so less money - who the hell cared for that..? We never had these delicious pizzas, these smorgasbord of cuisines we now have but we cherished drinking the glass of hot milk that mom always got ready for us - we cherished the home made food - Oh..yes - we cherished a glass of "water" and not a bottle of "sprite" to quench our thirst!
With Time, Empathy we possessed turned to Sympathy and gradually Sympathy changed to Antipathy. "If thou fittest, thou survive." Sadly, most of us interpreted the adage, as if, asking us to be selfish - to just surpass our counterparts in each and every field by any crooked means possible - to be friendly with a person as per the demands of the hour, only to betray just an hour later. Thoughts are so confined to self thinking and selfish interests now...!! Comes the first turn in the journey of Life and we see two budding friends; the very next turn shows them becoming strangers... There is a point to make friends - We in our pursuit of achieving a class are drilling the very path we are treading on... Daily, we add a new sophistication to our inventories but obliviously take yet another step to pain and suffering - yet another artificial pleasure to make a real "Life" more unreal - isn't it..? Just ponder over, for once atleast; just focus your roving eyes on the vista that shows you glimpses of your past - Give it a thought... Life is meant to be enjoyed with your family and friends. Don't waste yours, chasing materialistic and lifeless sophistications - Oh Man, your stay here is temporary - ENJOY IT BEFORE IT'S TOO LATE!
"Life it seems goes too fast,
Oh! Do you remember what went last?
Stop - a while - and watch a child at play,
And cherish the simplicity along the way."
- -
To get ya nostalgic, Here I quote Heart throbbing verses of SKC, just see if you can sense the Rhythm Divine...;)


बार-बार आती है मुझको मधुर याद बचपन तेरी।
गया ले गया तू जीवन की सबसे मस्त खुशी मेरी॥
चिंता-रहित खेलना-खाना वह फिरना निर्भय स्वच्छंद।
कैसे भूला जा सकता है बचपन का अतुलित आनंद?
ऊँच-नीच का ज्ञान नहीं था छुआछूत किसने जानी?
बनी हुई थी वहाँ झोंपड़ी और चीथड़ों में रानी॥
किये दूध के कुल्ले मैंने चूस अँगूठा सुधा पिया।
किलकारी किल्लोल मचाकर सूना घर आबाद किया॥
रोना और मचल जाना भी क्या आनंद दिखाते थे।
बड़े-बड़े मोती-से आँसू जयमाला पहनाते थे॥
मैं रोई, माँ काम छोड़कर आईं, मुझको उठा लिया।
झाड़-पोंछ कर चूम-चूम कर गीले गालों को सुखा दिया॥
दादा ने चंदा दिखलाया नेत्र नीर-युत दमक उठे।
धुली हुई मुस्कान देख कर सबके चेहरे चमक उठे॥
वह सुख का साम्राज्य छोड़कर मैं मतवाली बड़ी हुई।
लुटी हुई, कुछ ठगी हुई-सी दौड़ द्वार पर खड़ी हुई॥
लाजभरी आँखें थीं मेरी मन में उमँग रँगीली थी।
तान रसीली थी कानों में चंचल छैल छबीली थी॥
दिल में एक चुभन-सी भी थी यह दुनिया अलबेली थी।
मन में एक पहेली थी मैं सब के बीच अकेली थी॥
मिला, खोजती थी जिसको हे बचपन! ठगा दिया तूने।
अरे! जवानी के फंदे में मुझको फँसा दिया तूने॥
सब गलियाँ उसकी भी देखीं उसकी खुशियाँ न्यारी हैं।
प्यारी, प्रीतम की रँग-रलियों की स्मृतियाँ भी प्यारी हैं॥
माना मैंने युवा-काल का जीवन खूब निराला है।
आकांक्षा, पुरुषार्थ, ज्ञान का उदय मोहनेवाला है॥
किंतु यहाँ झंझट है भारी युद्ध-क्षेत्र संसार बना।
चिंता के चक्कर में पड़कर जीवन भी है भार बना॥
आ जा बचपन! एक बार फिर दे दे अपनी निर्मल शांति।
व्याकुल व्यथा मिटानेवाली वह अपनी प्राकृत विश्रांति॥
वह भोली-सी मधुर सरलता वह प्यारा जीवन निष्पाप।
क्या आकर फिर मिटा सकेगा तू मेरे मन का संताप?
मैं बचपन को बुला रही थी बोल उठी बिटिया मेरी।
नंदन वन-सी फूल उठी यह छोटी-सी कुटिया मेरी॥'
माँ ओ' कहकर बुला रही थी मिट्टी खाकर आयी थी।
कुछ मुँह में कुछ लिये हाथ में मुझे खिलाने लायी थी॥
पुलक रहे थे अंग, दृगों में कौतुहल था छलक रहा।
मुँह पर थी आह्लाद-लालिमा विजय-गर्व था झलक रहा॥
मैंने पूछा 'यह क्या लायी?' बोल उठी वह 'माँ, काओ'।
हुआ प्रफुल्लित हृदय खुशी से मैंने कहा - 'तुम्हीं खाओ'॥
पाया मैंने बचपन फिर से बचपन बेटी बन आया।
उसकी मंजुल मूर्ति देखकर मुझ में नवजीवन आया॥
मैं भी उसके साथ खेलती खाती हूँ, तुतलाती हूँ।
मिलकर उसके साथ स्वयं मैं भी बच्ची बन जाती हूँ॥
जिसे खोजती थी बरसों से अब जाकर उसको पाया।
भाग गया था मुझे छोड़कर वह बचपन फिर से आया॥
- सुभद्रा कुमारी चौहान
चिंता-रहित खेलना-खाना वह फिरना निर्भय स्वच्छंद।
कैसे भूला जा सकता है बचपन का अतुलित आनंद?
ऊँच-नीच का ज्ञान नहीं था छुआछूत किसने जानी?
बनी हुई थी वहाँ झोंपड़ी और चीथड़ों में रानी॥
किये दूध के कुल्ले मैंने चूस अँगूठा सुधा पिया।
किलकारी किल्लोल मचाकर सूना घर आबाद किया॥
रोना और मचल जाना भी क्या आनंद दिखाते थे।
बड़े-बड़े मोती-से आँसू जयमाला पहनाते थे॥
मैं रोई, माँ काम छोड़कर आईं, मुझको उठा लिया।
झाड़-पोंछ कर चूम-चूम कर गीले गालों को सुखा दिया॥
दादा ने चंदा दिखलाया नेत्र नीर-युत दमक उठे।
धुली हुई मुस्कान देख कर सबके चेहरे चमक उठे॥
वह सुख का साम्राज्य छोड़कर मैं मतवाली बड़ी हुई।
लुटी हुई, कुछ ठगी हुई-सी दौड़ द्वार पर खड़ी हुई॥
लाजभरी आँखें थीं मेरी मन में उमँग रँगीली थी।
तान रसीली थी कानों में चंचल छैल छबीली थी॥
दिल में एक चुभन-सी भी थी यह दुनिया अलबेली थी।
मन में एक पहेली थी मैं सब के बीच अकेली थी॥
मिला, खोजती थी जिसको हे बचपन! ठगा दिया तूने।
अरे! जवानी के फंदे में मुझको फँसा दिया तूने॥
सब गलियाँ उसकी भी देखीं उसकी खुशियाँ न्यारी हैं।
प्यारी, प्रीतम की रँग-रलियों की स्मृतियाँ भी प्यारी हैं॥
माना मैंने युवा-काल का जीवन खूब निराला है।
आकांक्षा, पुरुषार्थ, ज्ञान का उदय मोहनेवाला है॥
किंतु यहाँ झंझट है भारी युद्ध-क्षेत्र संसार बना।
चिंता के चक्कर में पड़कर जीवन भी है भार बना॥
आ जा बचपन! एक बार फिर दे दे अपनी निर्मल शांति।
व्याकुल व्यथा मिटानेवाली वह अपनी प्राकृत विश्रांति॥
वह भोली-सी मधुर सरलता वह प्यारा जीवन निष्पाप।
क्या आकर फिर मिटा सकेगा तू मेरे मन का संताप?
मैं बचपन को बुला रही थी बोल उठी बिटिया मेरी।
नंदन वन-सी फूल उठी यह छोटी-सी कुटिया मेरी॥'
माँ ओ' कहकर बुला रही थी मिट्टी खाकर आयी थी।
कुछ मुँह में कुछ लिये हाथ में मुझे खिलाने लायी थी॥
पुलक रहे थे अंग, दृगों में कौतुहल था छलक रहा।
मुँह पर थी आह्लाद-लालिमा विजय-गर्व था झलक रहा॥
मैंने पूछा 'यह क्या लायी?' बोल उठी वह 'माँ, काओ'।
हुआ प्रफुल्लित हृदय खुशी से मैंने कहा - 'तुम्हीं खाओ'॥
पाया मैंने बचपन फिर से बचपन बेटी बन आया।
उसकी मंजुल मूर्ति देखकर मुझ में नवजीवन आया॥
मैं भी उसके साथ खेलती खाती हूँ, तुतलाती हूँ।
मिलकर उसके साथ स्वयं मैं भी बच्ची बन जाती हूँ॥
जिसे खोजती थी बरसों से अब जाकर उसको पाया।
भाग गया था मुझे छोड़कर वह बचपन फिर से आया॥
- सुभद्रा कुमारी चौहान
Subscribe to:
Posts (Atom)


