SlideShare a Scribd company logo
code optimization techniques
● A substantial portion of a knowledge
worker's life may be spent waiting for a
computer program to produce output.
● Users and organizations control their wait time
by purchasing faster computers, adding memory, or using
faster network connections.
● Developers of application programs have a responsibility to
design their programs make the best use of these limited and
expensive resources.
What Is Code Optimization
● Optimization is the process of transforming a piece of code to make
it more efficient without changing its output
● Code optimization is a set of methods for code modification that
improves the code quality and efficiency.
● Optimization aims at -smaller size
-less memory consumption
-rapid executions (only few I/O operations)
Where To Optimize
● Check which portion or which module of the program is
running slow or using huge memory.
● If each part is separately being optimized then the total
programme will automatically get optimised.
● Optimization should be done on those part of program that
are run the most,especially on those methods which are called
repeatedly
Code Optimization Techniques
A program consist of :
• variables
• control statements
decision
loops
• functions
we need to optimize all these parts to run the program faster
Variable
The C compilers support the basic types
char,
short,
int,
long (signed and unsigned),
float and
double.
Using the most appropriate type for variables is very important, as it can reduce code
and data size and increase performance considerably.
Integers
Use unsigned int instead of int if we know the value will never be negative.
Some processors can handle unsigned integer arithmetic considerably faster than signed
So, the best declaration for an int variable in a tight loop would be:
unsigned int variable_name;
integer arithmetic is much faster than floating-point arithmetic, as it can usually be
done directly by the processor, rather than relying on external FPUs or floating point
math libraries.
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.
● The compiler cannot cache the value of a global variable in a register, resulting in
extra loads and stores when globals are used.
int f(void);
int g(void);
int errs;
void test1(void)
{
errs += f();
errs += g();
}
Here a function uses global
variables heavily
Global variables
int f(void);
int g(void);
int errs;
void test1(void)
{
errs += f();
errs += g();
}
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
void test2(void)
{
unsigned int localerrs = errs;
localerrs += f();
localerrs += g();
errs = localerrs;
}
Try it out….
Write a c program to find sum of N integer
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,sum=0,i;
for(i=0;i<n;i++)
sum=sum+i;
printf("Sum:%d",sum);
getch();
}
Try it out….
write a c program to find sum of N integer
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,sum=0,i;
for(i=0;i<n;i++)
sum=sum+i;
printf("Sum:%d",sum);
getch();
}
#include<stdio.h>
#include<conio.h>
main()
{
unsigned int n=10,sum=0,i;
for(i=0;i<n;i++)
sum=sum+i;
printf("Sum:%d",sum);
getch();
}
#include <stdio.h>
int area=100;
int square(){
int x=10;
return x*x; }
int rectangle(){
int l=10,b=20;
int ar=2*(l+b);
return ar;
}
main()
{
area=area+square();
area=area+rectangle();
printf("area:%d",area);
}
Try it out
Write a program to find total area of a plot having a square shaped and rectangular shaped plot
global variable
#include <stdio.h>
int area=100;
int square(){
int x=10;
return x*x; }
int rectangle(){
int l=10,b=20;
int ar=2*(l+b);
return ar;
}
Try it out
Write a program to find total area of a plot having a square shaped and rectangular shaped plot
Making global variable local
main()
{
unsigned int localarea=area;
area=area+square();
area=area+rectangle();
printf("area:%d",area);
area=localarea;
}
Using array indices
switch ( queue ) {
case 0 : letter = 'W';
break;
case 1 : letter = 'S';
break;
case 2 : letter = 'U';
break;
}
if ( queue == 0 )
letter = 'W';
else if ( queue == 1
)
letter = 'S';
else
letter = 'U';
If you wished to set a variable to a particular character, depending upon the value of
something, you might do this:
Using array indices
A neater (and quicker) method is to simply use the value as an
index into a character array, e.g.:
static char *classes="WSU";
letter = classes[queue];
Control Statements
switch() instead of if...else...
For large decisions involving if...else...else..., like this:
if( val == 1)
dostuff1();
else if (val == 2)
dostuff2();
else if (val == 3)
dostuff3();
Control Statements
switch() instead of if...else...
It may be faster to use a switch
switch( val )
{
case 1: dostuff1(); break;
case 2: dostuff2(); break;
case 3: dostuff3(); break;
}
Try it out...
Write a c program to set index to english alphabet
#include<stdio.h>
#include<string.h>
main()
{char letter; int ch;
printf("enter the pos");
scanf("%d",&ch);
switch(ch){
case 0:letter='a';break;
case 1:letter='b'; break;
- - -
}
printf("%c",letter); }
Try it out...
write a c program to set index to english alphabet
#include<stdio.h>
#include<string.h>
main()
{char letter; int ch;
printf("enter the pos");
scanf("%d",&ch);
switch(ch){
case 0:letter='a';break;
case 1:letter='b'; break;
- - -
}
printf("%c",letter); }
#include<stdio.h>
#include<conio.h>
main()
{
char *classes="abcdefghi";
int i,ch,letter[26],queue=0;;
for(i=1;i<=26;i++) {
letter[i]=classes[queue];
queue++;
}
printf("enter the position");
scanf("%d",&ch);
printf("%c",letter[ch]);
getch(); }
Loop jamming
Never use two loops where one will suffice
for(i=0; i<100; i++){
stuff();
}
for(i=0; i<100; i++){
morestuff();
}
Loop jamming
It will be better to do this way:
for(i=0; i<100; i++){
stuff();
}
for(i=0; i<100; i++){
morestuff();
}
for(i=0; i<100; ++)
{
stuff();
morestuff();
}
Try it out….
main()
{int a[100],sum=0,product=1,i;
printf("enter elements into array");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
sum=sum+a[i];
for(i=0;i<5;i++)
product=product*a[i];
printf("nsum:%d n
product:%d",sum,product); }
Write program to find sum and product of elements in a array
Try it out….
main()
{int a[100],sum=0,product=1,i;
printf("enter elements into array");
for(i=0;i<5;i++)
scanf("%d",&a[i]);
for(i=0;i<5;i++)
sum=sum+a[i];
for(i=0;i<5;i++)
product=product*a[i];
printf("nsum:%d n
product:%d",sum,product); }
Write program to find sum and product of elements in a array
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
product=product*a[i];
}
Function Looping
If a function is often called from within a loop ,it may be possible to put that loop
inside the function to cut down the overhead of calling the function repeatedly
for(i=0 ; i<100 ; i++)
{
func(t,i);
}
-
-
-
void func(int w,d)
{
lots of stuff.
}
func(t);
-
-
void func(w)
{
for(i=0 ; i<100 ; i++)
{
//lots of stuff.
}
}
Try it out
Write a program to find sum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,i,total=0;
for(i=0;i<10;i++)
total+=sum(i);
printf("n sum is:%d",total);
getch();
}
sum(int i)
{ int sum=0;
sum=sum+i;
}
Try it out
Write a program to find sum of n numbers
#include<stdio.h>
#include<conio.h>
main()
{
int n=10,i,total=0;
for(i=0;i<10;i++)
total += sum(i);
printf("n sum is:%d",total);
getch();
}
sum(int i)
{ int sum=0;
sum=sum+i;
}
main()
{ int total=0;
total=sum();
printf("n sum is:%d",total);
getch();
}
int sum()
{ int sum=0,i;
for(i=0;i<10;i++)
sum=sum+i;
return sum;
}
Faster for() loops
Ordinarily, we used to code a simple for() loop like this:
for( i=0; i<10; i++){ ... } [ i loops through the values 0,1,2,3,4,5,6,7,8,9 ]
If we needn't care about the order of the loop counter, we can do this instead:
for( i=10; ; i-- ) { ... }
Using this code, i loops through the values 9,8,7,6,5,4,3,2,1,0, and the loop should be
faster.
This works because it is quicker to process i--
Try it out….
Write a program to find factorial of a number
main()
{
int factorial=0,n=3;
factorial=fact(n);
clrscr();
printf("%d",factorial);
getch();
}
fact(int n)
{
int i,fact=1;
for(i=0;i<n;i++)
fact*=i;
return fact;
}
Try it out….
Write a program to find factorial of a number
main()
{
int factorial=0,n=3;
factorial=fact(n);
clrscr();
printf("%d",factorial);
getch();
}
fact(int n)
{
int i,fact=1;
for(i=0;i<n;i++)
fact*=i;
return fact;
}
main()
{ int
factorial=0,n=3;
factorial=fact(n);
clrscr();
printf("%d",factorial);
getch();
}
fact(int n)
{ int i,fact=1;
for(i=n;i!=0;i--)
fact*=i;
return fact*;
}
loop unrolling
● Small loops can be unrolled for higher performance.
● If the loop iterates only a few times, it can be fully unrolled, so that the loop
overhead completely disappears.
This can make a big difference. It is well known that unrolling loops can produce
considerable savings, e.g.:
for(i=0; i<3; i++){
something(i);
}
something(0);
something(1);
something(2);
Early loop breaking
It is often not necessary to process the entirety of a loop.
Example, if we are searching an array for a particular item, break out of the loop as
soon as we have got what we need.
Example: this loop searches a list of 10000 numbers to see if there is a -99 in it.
found = FALSE;
for(i=0;i<10000;i++)
{
if( list[i] == -99 )
{
found = TRUE;
}
}
if( found ) printf("Yes,
there is a -99. Hooray!n");
found = FALSE;
for(i=0; i<10000; i++)
{
if( list[i] == -99 )
{
found = TRUE;
break;
}
}
if( found )
printf("Yes, there is a -
99. Hooray!n");
Try it out
write a program to find position of an element in array
main( )
{ int arr[10],i,element,f=0;
printf("enter the elements");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("enter the elements to search");
scanf("%d",&element);
for(i=0;i<10;i++)
{ if(arr[i]==element)
f=1;
}
if(f = =1) printf("element found");
}
Try it out
write a program to find position of an element in array
main( )
{ int arr[10],i,element,f=0;
printf("enter the elements");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("enter the elements to search");
scanf("%d",&element);
for(i=0;i<10;i++)
{ if(arr[i]==element)
f=1;
}
if(f = =1) printf("element found");
}
early loop
breaking
main( ) {
int arr[10],i,element,f=0;
printf("enter the elements");
for(i=0;i<10;i++)
scanf("%d",&arr[i]);
printf("enter the elements to search");
scanf("%d",&element);
for(i=0;i<10;i++)
{ if(arr[i]==element)
{ f=1; break;}
}
if(f = =1) printf("element found");
}
Code Motion
Code motion involves identifying bits of code that occur within loops, but need only
be executed once during that particular loop.
For example,
void shift_char(char *str){
int i;
for(i=0;i<strlen(str);i++){
str[i]++;
}
}
void shift_char(char *str){
int i;
int len=strlen(str)
for(i=0;i<len;i++){
str[i]++;
}
}
Try it out
Write a program to search a character in a string
main()
{ char arr[10];
int i,ch,f=0,len;
printf("enter the string");
scanf("%s",&arr);
printf("enter the character to
search");
scanf("%s",&ch);
len=strlen(arr);
for(i=0;i<len;i++)
{ if(arr[i]==ch)
{ f=1; break;}
}
if(f==1) printf("element found");
}
function strlen is called once and set
to variable len
Function Design
● keep functions small and simple.
● This enables the compiler to perform optimizations
such as register allocation more efficiently.
function call overhead
● There is some limitation upto which words of argument
can be passed to a function in register.
● If the argument limitation is 4 then the 5th and
subsequent words are passed on the stack.
int f2(int a, int b, int c, int d, int e, int f)
{
return a + b + c + d + e + f;
}
int g2(void) {
return f2(1, 2, 3, 4, 5, 6);
}
The fifth and sixth parameters are stored on the stack in g2, and reloaded
in f2, costing two memory accesses per parameter.
int f1(int a, int b, int c, int d)
{
return a + b + c + d;
}
int g1(void) {
return f1(1, 2, 3, 4);
}
This code works fine.
Minimizing parameter passing overhead
To minimize the overhead of passing parameters to functions:
● Try to ensure that small functions take four or fewer arguments.This will reduce
the number of parameters and increase readability.
● Pass pointers to structures instead of passing the structure itself.
void print_data_of_a_structure ( const Thestruct *data_pointer)
{
...printf contents of the structure...
}
● Avoid functions with a variable number of parameters. Those functions effectively
pass all their arguments on the stack.
Try it out
write a c program to print content of a structure
struct student
{ int id;
char name[20];
float percentage };
void func(struct student *record);
int main()
{ struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0; }
void func(struct student *record)
{
printf(" Id is: %d n", record->id);
printf(" Name is: %s n", record->name);
printf(" Percentage is: %f n", record->percentage);
}
struct student
{ int id;
char name[20];
float percentage; };
void func(struct student record);
int main()
{ struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0; }
void func(struct student record)
{ printf(" Id is: %d n", record.id);
printf(" Name is: %s n", record.name);
printf(" Percentage is: %f n",
record.percentage);
}
Pass pointers of a
structure
Inline function
● Inlining is the process by which the contents of a function are copied and pasted
instead of a traditional call to that function.
● This form of optimization avoids the overhead of function calls, by eliminating the
need to jump, create a new stack frame, and reverse this process at the end of the
function.
Inline int square(int x)
{
return x*x
}
#include<math.h>
double length(int x,int y)
{
return sqrt(square(x)*square(y))
}
Try it out
write a program to implement square root of x2+y2
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
int x=4,y=3,a;
a= sqrt(square(x)+square(y));
clrscr();
printf("n %d",a);
getch();
}
int square(int x)
{ return x*x;
}
#include <stdio.h>
#include<math.h>
int main() {
int tmp,x=4,y=3;
tmp = sqrt(square(x)+square(y));
printf("square val=%dn", tmp);
return 0;
}
int inline square(int x) {
return x*x;
}
Inline function
Advantage of using inline function
● No function call overhead
As the code is substituted directly ,there is no overhead like saving and storing
register
● Lower argument evaluation overhead
The overhead of parameter passing is generally lower,since it is not
necessary to copy variables
THE END

More Related Content

What's hot

Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
RAJWANT KAUR
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rathSANTOSH RATH
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
Hazrat Bilal
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
nikshaikh786
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
Aditya Nihal Kumar Singh
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
MomenMostafa
 
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYCS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
Radha Maruthiyan
 
Arrays
ArraysArrays
Arrays
fahadshakeel
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shorting
argusacademy
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysisVishal Singh
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manualSANTOSH RATH
 
lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
Rupendra Choudhary
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
Rahul Chugh
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
Rumman Ansari
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
Kathmandu University
 
Functions in c
Functions in cFunctions in c
Functions in c
Innovative
 

What's hot (20)

C lab excellent
C lab excellentC lab excellent
C lab excellent
 
Practical File of C Language
Practical File of C LanguagePractical File of C Language
Practical File of C Language
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Let us C (by yashvant Kanetkar) chapter 3 Solution
Let us C   (by yashvant Kanetkar) chapter 3 SolutionLet us C   (by yashvant Kanetkar) chapter 3 Solution
Let us C (by yashvant Kanetkar) chapter 3 Solution
 
Data structure lab manual
Data structure lab manualData structure lab manual
Data structure lab manual
 
Function & Recursion in C
Function & Recursion in CFunction & Recursion in C
Function & Recursion in C
 
8 arrays and pointers
8  arrays and pointers8  arrays and pointers
8 arrays and pointers
 
Functions
FunctionsFunctions
Functions
 
L7 pointers
L7 pointersL7 pointers
L7 pointers
 
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORYCS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
CS6311- PROGRAMMING & DATA STRUCTURE II LABORATORY
 
Arrays
ArraysArrays
Arrays
 
C programming array & shorting
C  programming array & shortingC  programming array & shorting
C programming array & shorting
 
Numerical analysis
Numerical analysisNumerical analysis
Numerical analysis
 
Data structure new lab manual
Data structure  new lab manualData structure  new lab manual
Data structure new lab manual
 
lets play with "c"..!!! :):)
lets play with "c"..!!! :):)lets play with "c"..!!! :):)
lets play with "c"..!!! :):)
 
Data Structures Using C Practical File
Data Structures Using C Practical File Data Structures Using C Practical File
Data Structures Using C Practical File
 
Tail Recursion in data structure
Tail Recursion in data structureTail Recursion in data structure
Tail Recursion in data structure
 
C program
C programC program
C program
 
Pointers [compatibility mode]
Pointers [compatibility mode]Pointers [compatibility mode]
Pointers [compatibility mode]
 
Functions in c
Functions in cFunctions in c
Functions in c
 

Viewers also liked

Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Hiring in startups - What you should know.
Hiring in startups - What you should know. Hiring in startups - What you should know.
Hiring in startups - What you should know.
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com little coder chapter - 6
Baabtra.com little coder   chapter - 6Baabtra.com little coder   chapter - 6
Baabtra.com little coder chapter - 6
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com little coder chapter - 3
Baabtra.com little coder   chapter - 3Baabtra.com little coder   chapter - 3
Baabtra.com little coder chapter - 3
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com little coder chapter - 4
Baabtra.com little coder   chapter - 4Baabtra.com little coder   chapter - 4
Baabtra.com little coder chapter - 4
baabtra.com - No. 1 supplier of quality freshers
 
What is Android
What is AndroidWhat is Android
Brain computer interface(neethu,bincy,sanooja)
Brain computer interface(neethu,bincy,sanooja)Brain computer interface(neethu,bincy,sanooja)
Brain computer interface(neethu,bincy,sanooja)
baabtra.com - No. 1 supplier of quality freshers
 
Cell phone jammer
Cell phone jammerCell phone jammer
Chapter 1 : Uses of Computer
Chapter  1 : Uses of ComputerChapter  1 : Uses of Computer

Viewers also liked (19)

Transaction
TransactionTransaction
Transaction
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Jquery
JqueryJquery
Jquery
 
Hiring in startups - What you should know.
Hiring in startups - What you should know. Hiring in startups - What you should know.
Hiring in startups - What you should know.
 
Oop cocepts
Oop coceptsOop cocepts
Oop cocepts
 
Database and types of database
Database and types of databaseDatabase and types of database
Database and types of database
 
Baabtra.com little coder chapter - 6
Baabtra.com little coder   chapter - 6Baabtra.com little coder   chapter - 6
Baabtra.com little coder chapter - 6
 
Inheritance
InheritanceInheritance
Inheritance
 
Baabtra.com little coder chapter - 3
Baabtra.com little coder   chapter - 3Baabtra.com little coder   chapter - 3
Baabtra.com little coder chapter - 3
 
Baabtra.com little coder chapter - 4
Baabtra.com little coder   chapter - 4Baabtra.com little coder   chapter - 4
Baabtra.com little coder chapter - 4
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Functions with heap and stack
Functions with heap and stackFunctions with heap and stack
Functions with heap and stack
 
Strctures,strings,pointers
Strctures,strings,pointersStrctures,strings,pointers
Strctures,strings,pointers
 
What is Android
What is AndroidWhat is Android
What is Android
 
Introduction to mysql part 2
Introduction to mysql part 2Introduction to mysql part 2
Introduction to mysql part 2
 
Brain computer interface(neethu,bincy,sanooja)
Brain computer interface(neethu,bincy,sanooja)Brain computer interface(neethu,bincy,sanooja)
Brain computer interface(neethu,bincy,sanooja)
 
Preprocessor
PreprocessorPreprocessor
Preprocessor
 
Cell phone jammer
Cell phone jammerCell phone jammer
Cell phone jammer
 
Chapter 1 : Uses of Computer
Chapter  1 : Uses of ComputerChapter  1 : Uses of Computer
Chapter 1 : Uses of Computer
 

Similar to Code optimization

An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
Tushar B Kute
 
Array Cont
Array ContArray Cont
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
Hemantha Kulathilake
 
C intro
C introC intro
C intro
Kamran
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
THE NORTHCAP UNIVERSITY
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
amrit47
 
C important questions
C important questionsC important questions
C important questions
JYOTI RANJAN PAL
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
 
7 functions
7  functions7  functions
7 functions
MomenMostafa
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
Functions
FunctionsFunctions
Functions
Swarup Boro
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
Chandrakant Divate
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
Wingston
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
MKalpanaDevi
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
Icaii Infotech
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
Linaro
 

Similar to Code optimization (20)

An imperative study of c
An imperative study of cAn imperative study of c
An imperative study of c
 
Array Cont
Array ContArray Cont
Array Cont
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
C intro
C introC intro
C intro
 
Fundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan KumariFundamentals of computer programming by Dr. A. Charan Kumari
Fundamentals of computer programming by Dr. A. Charan Kumari
 
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docxPROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
PROVIDE COMMENTS TO FELLOW STUDENTS ANSWERS AND PLEASE DON’T SAY G.docx
 
C important questions
C important questionsC important questions
C important questions
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
7 functions
7  functions7  functions
7 functions
 
Function in c program
Function in c programFunction in c program
Function in c program
 
functions
functionsfunctions
functions
 
Functions
FunctionsFunctions
Functions
 
Fundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptxFundamentals of functions in C program.pptx
Fundamentals of functions in C program.pptx
 
Advanced C - Part 2
Advanced C - Part 2Advanced C - Part 2
Advanced C - Part 2
 
Introduction to Basic C programming 01
Introduction to Basic C programming 01Introduction to Basic C programming 01
Introduction to Basic C programming 01
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Assignment c programming
Assignment c programmingAssignment c programming
Assignment c programming
 
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
BKK16-503 Undefined Behavior and Compiler Optimizations – Why Your Program St...
 

More from baabtra.com - No. 1 supplier of quality freshers

Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
baabtra.com - No. 1 supplier of quality freshers
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
baabtra.com - No. 1 supplier of quality freshers
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
baabtra.com - No. 1 supplier of quality freshers
 
Php database connectivity
Php database connectivityPhp database connectivity
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
baabtra.com - No. 1 supplier of quality freshers
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
baabtra.com - No. 1 supplier of quality freshers
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Blue brain
Blue brainBlue brain
5g
5g5g
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Baabtra soft skills
Baabtra soft skillsBaabtra soft skills

More from baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 
Baabtra soft skills
Baabtra soft skillsBaabtra soft skills
Baabtra soft skills
 

Recently uploaded

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
Tamralipta Mahavidyalaya
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
GeoBlogs
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
JosvitaDsouza2
 

Recently uploaded (20)

How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Home assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdfHome assignment II on Spectroscopy 2024 Answers.pdf
Home assignment II on Spectroscopy 2024 Answers.pdf
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
The geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideasThe geography of Taylor Swift - some ideas
The geography of Taylor Swift - some ideas
 
1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx1.4 modern child centered education - mahatma gandhi-2.pptx
1.4 modern child centered education - mahatma gandhi-2.pptx
 

Code optimization

  • 1.
  • 3. ● A substantial portion of a knowledge worker's life may be spent waiting for a computer program to produce output. ● Users and organizations control their wait time by purchasing faster computers, adding memory, or using faster network connections. ● Developers of application programs have a responsibility to design their programs make the best use of these limited and expensive resources.
  • 4. What Is Code Optimization ● Optimization is the process of transforming a piece of code to make it more efficient without changing its output ● Code optimization is a set of methods for code modification that improves the code quality and efficiency. ● Optimization aims at -smaller size -less memory consumption -rapid executions (only few I/O operations)
  • 5. Where To Optimize ● Check which portion or which module of the program is running slow or using huge memory. ● If each part is separately being optimized then the total programme will automatically get optimised. ● Optimization should be done on those part of program that are run the most,especially on those methods which are called repeatedly
  • 6. Code Optimization Techniques A program consist of : • variables • control statements decision loops • functions we need to optimize all these parts to run the program faster
  • 7. Variable The C compilers support the basic types char, short, int, long (signed and unsigned), float and double. Using the most appropriate type for variables is very important, as it can reduce code and data size and increase performance considerably.
  • 8. Integers Use unsigned int instead of int if we know the value will never be negative. Some processors can handle unsigned integer arithmetic considerably faster than signed So, the best declaration for an int variable in a tight loop would be: unsigned int variable_name; integer arithmetic is much faster than floating-point arithmetic, as it can usually be done directly by the processor, rather than relying on external FPUs or floating point math libraries.
  • 9. 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. ● The compiler cannot cache the value of a global variable in a register, resulting in extra loads and stores when globals are used. int f(void); int g(void); int errs; void test1(void) { errs += f(); errs += g(); } Here a function uses global variables heavily
  • 10. Global variables int f(void); int g(void); int errs; void test1(void) { errs += f(); errs += g(); } 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 void test2(void) { unsigned int localerrs = errs; localerrs += f(); localerrs += g(); errs = localerrs; }
  • 11. Try it out…. Write a c program to find sum of N integer #include<stdio.h> #include<conio.h> main() { int n=10,sum=0,i; for(i=0;i<n;i++) sum=sum+i; printf("Sum:%d",sum); getch(); }
  • 12. Try it out…. write a c program to find sum of N integer #include<stdio.h> #include<conio.h> main() { int n=10,sum=0,i; for(i=0;i<n;i++) sum=sum+i; printf("Sum:%d",sum); getch(); } #include<stdio.h> #include<conio.h> main() { unsigned int n=10,sum=0,i; for(i=0;i<n;i++) sum=sum+i; printf("Sum:%d",sum); getch(); }
  • 13. #include <stdio.h> int area=100; int square(){ int x=10; return x*x; } int rectangle(){ int l=10,b=20; int ar=2*(l+b); return ar; } main() { area=area+square(); area=area+rectangle(); printf("area:%d",area); } Try it out Write a program to find total area of a plot having a square shaped and rectangular shaped plot global variable
  • 14. #include <stdio.h> int area=100; int square(){ int x=10; return x*x; } int rectangle(){ int l=10,b=20; int ar=2*(l+b); return ar; } Try it out Write a program to find total area of a plot having a square shaped and rectangular shaped plot Making global variable local main() { unsigned int localarea=area; area=area+square(); area=area+rectangle(); printf("area:%d",area); area=localarea; }
  • 15. Using array indices switch ( queue ) { case 0 : letter = 'W'; break; case 1 : letter = 'S'; break; case 2 : letter = 'U'; break; } if ( queue == 0 ) letter = 'W'; else if ( queue == 1 ) letter = 'S'; else letter = 'U'; If you wished to set a variable to a particular character, depending upon the value of something, you might do this:
  • 16. Using array indices A neater (and quicker) method is to simply use the value as an index into a character array, e.g.: static char *classes="WSU"; letter = classes[queue];
  • 17. Control Statements switch() instead of if...else... For large decisions involving if...else...else..., like this: if( val == 1) dostuff1(); else if (val == 2) dostuff2(); else if (val == 3) dostuff3();
  • 18. Control Statements switch() instead of if...else... It may be faster to use a switch switch( val ) { case 1: dostuff1(); break; case 2: dostuff2(); break; case 3: dostuff3(); break; }
  • 19. Try it out... Write a c program to set index to english alphabet #include<stdio.h> #include<string.h> main() {char letter; int ch; printf("enter the pos"); scanf("%d",&ch); switch(ch){ case 0:letter='a';break; case 1:letter='b'; break; - - - } printf("%c",letter); }
  • 20. Try it out... write a c program to set index to english alphabet #include<stdio.h> #include<string.h> main() {char letter; int ch; printf("enter the pos"); scanf("%d",&ch); switch(ch){ case 0:letter='a';break; case 1:letter='b'; break; - - - } printf("%c",letter); } #include<stdio.h> #include<conio.h> main() { char *classes="abcdefghi"; int i,ch,letter[26],queue=0;; for(i=1;i<=26;i++) { letter[i]=classes[queue]; queue++; } printf("enter the position"); scanf("%d",&ch); printf("%c",letter[ch]); getch(); }
  • 21. Loop jamming Never use two loops where one will suffice for(i=0; i<100; i++){ stuff(); } for(i=0; i<100; i++){ morestuff(); }
  • 22. Loop jamming It will be better to do this way: for(i=0; i<100; i++){ stuff(); } for(i=0; i<100; i++){ morestuff(); } for(i=0; i<100; ++) { stuff(); morestuff(); }
  • 23. Try it out…. main() {int a[100],sum=0,product=1,i; printf("enter elements into array"); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) sum=sum+a[i]; for(i=0;i<5;i++) product=product*a[i]; printf("nsum:%d n product:%d",sum,product); } Write program to find sum and product of elements in a array
  • 24. Try it out…. main() {int a[100],sum=0,product=1,i; printf("enter elements into array"); for(i=0;i<5;i++) scanf("%d",&a[i]); for(i=0;i<5;i++) sum=sum+a[i]; for(i=0;i<5;i++) product=product*a[i]; printf("nsum:%d n product:%d",sum,product); } Write program to find sum and product of elements in a array for(i=0;i<5;i++) { scanf("%d",&a[i]); sum=sum+a[i]; product=product*a[i]; }
  • 25. Function Looping If a function is often called from within a loop ,it may be possible to put that loop inside the function to cut down the overhead of calling the function repeatedly for(i=0 ; i<100 ; i++) { func(t,i); } - - - void func(int w,d) { lots of stuff. } func(t); - - void func(w) { for(i=0 ; i<100 ; i++) { //lots of stuff. } }
  • 26. Try it out Write a program to find sum of n numbers #include<stdio.h> #include<conio.h> main() { int n=10,i,total=0; for(i=0;i<10;i++) total+=sum(i); printf("n sum is:%d",total); getch(); } sum(int i) { int sum=0; sum=sum+i; }
  • 27. Try it out Write a program to find sum of n numbers #include<stdio.h> #include<conio.h> main() { int n=10,i,total=0; for(i=0;i<10;i++) total += sum(i); printf("n sum is:%d",total); getch(); } sum(int i) { int sum=0; sum=sum+i; } main() { int total=0; total=sum(); printf("n sum is:%d",total); getch(); } int sum() { int sum=0,i; for(i=0;i<10;i++) sum=sum+i; return sum; }
  • 28. Faster for() loops Ordinarily, we used to code a simple for() loop like this: for( i=0; i<10; i++){ ... } [ i loops through the values 0,1,2,3,4,5,6,7,8,9 ] If we needn't care about the order of the loop counter, we can do this instead: for( i=10; ; i-- ) { ... } Using this code, i loops through the values 9,8,7,6,5,4,3,2,1,0, and the loop should be faster. This works because it is quicker to process i--
  • 29. Try it out…. Write a program to find factorial of a number main() { int factorial=0,n=3; factorial=fact(n); clrscr(); printf("%d",factorial); getch(); } fact(int n) { int i,fact=1; for(i=0;i<n;i++) fact*=i; return fact; }
  • 30. Try it out…. Write a program to find factorial of a number main() { int factorial=0,n=3; factorial=fact(n); clrscr(); printf("%d",factorial); getch(); } fact(int n) { int i,fact=1; for(i=0;i<n;i++) fact*=i; return fact; } main() { int factorial=0,n=3; factorial=fact(n); clrscr(); printf("%d",factorial); getch(); } fact(int n) { int i,fact=1; for(i=n;i!=0;i--) fact*=i; return fact*; }
  • 31. loop unrolling ● Small loops can be unrolled for higher performance. ● If the loop iterates only a few times, it can be fully unrolled, so that the loop overhead completely disappears. This can make a big difference. It is well known that unrolling loops can produce considerable savings, e.g.: for(i=0; i<3; i++){ something(i); } something(0); something(1); something(2);
  • 32. Early loop breaking It is often not necessary to process the entirety of a loop. Example, if we are searching an array for a particular item, break out of the loop as soon as we have got what we need. Example: this loop searches a list of 10000 numbers to see if there is a -99 in it. found = FALSE; for(i=0;i<10000;i++) { if( list[i] == -99 ) { found = TRUE; } } if( found ) printf("Yes, there is a -99. Hooray!n"); found = FALSE; for(i=0; i<10000; i++) { if( list[i] == -99 ) { found = TRUE; break; } } if( found ) printf("Yes, there is a - 99. Hooray!n");
  • 33. Try it out write a program to find position of an element in array main( ) { int arr[10],i,element,f=0; printf("enter the elements"); for(i=0;i<10;i++) scanf("%d",&arr[i]); printf("enter the elements to search"); scanf("%d",&element); for(i=0;i<10;i++) { if(arr[i]==element) f=1; } if(f = =1) printf("element found"); }
  • 34. Try it out write a program to find position of an element in array main( ) { int arr[10],i,element,f=0; printf("enter the elements"); for(i=0;i<10;i++) scanf("%d",&arr[i]); printf("enter the elements to search"); scanf("%d",&element); for(i=0;i<10;i++) { if(arr[i]==element) f=1; } if(f = =1) printf("element found"); } early loop breaking main( ) { int arr[10],i,element,f=0; printf("enter the elements"); for(i=0;i<10;i++) scanf("%d",&arr[i]); printf("enter the elements to search"); scanf("%d",&element); for(i=0;i<10;i++) { if(arr[i]==element) { f=1; break;} } if(f = =1) printf("element found"); }
  • 35. Code Motion Code motion involves identifying bits of code that occur within loops, but need only be executed once during that particular loop. For example, void shift_char(char *str){ int i; for(i=0;i<strlen(str);i++){ str[i]++; } } void shift_char(char *str){ int i; int len=strlen(str) for(i=0;i<len;i++){ str[i]++; } }
  • 36. Try it out Write a program to search a character in a string main() { char arr[10]; int i,ch,f=0,len; printf("enter the string"); scanf("%s",&arr); printf("enter the character to search"); scanf("%s",&ch); len=strlen(arr); for(i=0;i<len;i++) { if(arr[i]==ch) { f=1; break;} } if(f==1) printf("element found"); } function strlen is called once and set to variable len
  • 37. Function Design ● keep functions small and simple. ● This enables the compiler to perform optimizations such as register allocation more efficiently. function call overhead ● There is some limitation upto which words of argument can be passed to a function in register. ● If the argument limitation is 4 then the 5th and subsequent words are passed on the stack.
  • 38. int f2(int a, int b, int c, int d, int e, int f) { return a + b + c + d + e + f; } int g2(void) { return f2(1, 2, 3, 4, 5, 6); } The fifth and sixth parameters are stored on the stack in g2, and reloaded in f2, costing two memory accesses per parameter. int f1(int a, int b, int c, int d) { return a + b + c + d; } int g1(void) { return f1(1, 2, 3, 4); } This code works fine.
  • 39. Minimizing parameter passing overhead To minimize the overhead of passing parameters to functions: ● Try to ensure that small functions take four or fewer arguments.This will reduce the number of parameters and increase readability. ● Pass pointers to structures instead of passing the structure itself. void print_data_of_a_structure ( const Thestruct *data_pointer) { ...printf contents of the structure... } ● Avoid functions with a variable number of parameters. Those functions effectively pass all their arguments on the stack.
  • 40. Try it out write a c program to print content of a structure struct student { int id; char name[20]; float percentage }; void func(struct student *record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(&record); return 0; } void func(struct student *record) { printf(" Id is: %d n", record->id); printf(" Name is: %s n", record->name); printf(" Percentage is: %f n", record->percentage); } struct student { int id; char name[20]; float percentage; }; void func(struct student record); int main() { struct student record; record.id=1; strcpy(record.name, "Raju"); record.percentage = 86.5; func(record); return 0; } void func(struct student record) { printf(" Id is: %d n", record.id); printf(" Name is: %s n", record.name); printf(" Percentage is: %f n", record.percentage); } Pass pointers of a structure
  • 41. Inline function ● Inlining is the process by which the contents of a function are copied and pasted instead of a traditional call to that function. ● This form of optimization avoids the overhead of function calls, by eliminating the need to jump, create a new stack frame, and reverse this process at the end of the function. Inline int square(int x) { return x*x } #include<math.h> double length(int x,int y) { return sqrt(square(x)*square(y)) }
  • 42. Try it out write a program to implement square root of x2+y2 #include<stdio.h> #include<conio.h> #include<math.h> main() { int x=4,y=3,a; a= sqrt(square(x)+square(y)); clrscr(); printf("n %d",a); getch(); } int square(int x) { return x*x; } #include <stdio.h> #include<math.h> int main() { int tmp,x=4,y=3; tmp = sqrt(square(x)+square(y)); printf("square val=%dn", tmp); return 0; } int inline square(int x) { return x*x; } Inline function
  • 43. Advantage of using inline function ● No function call overhead As the code is substituted directly ,there is no overhead like saving and storing register ● Lower argument evaluation overhead The overhead of parameter passing is generally lower,since it is not necessary to copy variables