|
|
#11 | ||||||||
|
Junior Member
|
/*"Write a C function that multiplies an input integer by 5 and returns the result. The function must not use the multiplication operator. Optimize for speed."*/
#include<iostream.h> #include<conio.h> add(int); int main() { clrscr(); int a; cout<<"enter no:"; cin>>a; add(a); getch(); return 0; } int add(int a) { a=a+a+a+a+a; cout<<a; } |
||||||||
|
|
|
|
#12 | |||||||||
|
Senior Member
Location: London |
Quote:
eg. In Binary: 0000 0110 = 6 If we bit shift left by 1 bit we get this: 0000 1100 = 12 So shifting by 1 will double the number. Shifting by 2 will multiply it by 4, and so on. The bonus is that bit-shifting is very fast. In your case, multiplying by 5 there is only a very little difference but say you were to multiply by 50 using the same techniques, the bit shifting one is much faster. This is my version of your code: Code:
#include <iostream>
#include <time.h>
using namespace std;
int add(int);
int shift(int);
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock1-clock2;
double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
return diffms;
}
int main()
{
bool running = true;
while(running)
{
int a;
cout<<"Enter no (0 to exit):";
cin>>a;
if(a == 0)
running = false;
else
{
// Use a loop so that we can time the results
const int loops = 1000000;
int res = -1;
int i=0;
//-----------------
// Using Addition
clock_t begin=clock();
for(i=0; i<loops; ++i)
{
res = add(a);
}
clock_t end=clock();
cout << "Old Version Time elapsed: " << double(diffclock(end,begin)) << " ms Result:" << res << endl;
//---------------------
// Using Bit-shifting
begin=clock();
for(i=0; i<loops; ++i)
{
res = shift(a);
}
end=clock();
cout << "New Version Time elapsed: " << double(diffclock(end,begin)) << " ms Result:" << res << endl;
}
}
return 0;
}
int add(int a)
{
a=a+a+a+a+a;
return a;
}
int shift(int a)
{
return (a << 2) + a;
}
|
|||||||||
|
|
![]() |
«
Previous Thread
|
Next Thread
»
| Thread Tools | |
| Display Modes | |
|
|
Powered by vBulletin® Version 3.6.9
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
All times are GMT -8. The time now is 12:25 AM.


















Linear Mode

