473,796 Members | 2,677 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Same program in C and in C#. C# is faster than C. How Come ?

c
Hi every one,

Me and my Cousin were talking about C and C#, I love C and he loves
C#..and were talking C is ...blah blah...C# is Blah Blah ...etc

and then we decided to write a program that will calculate the
factorial of 10, 10 millions time and print the reusult in a file with
the name log.txt..

I wrote something like this

#include <stdio.h>
unsigned int fib (int n);

int main()
{
FILE *fp;
unsigned int loop =1 ;
if ( (fp = fopen( "log.txt", "a" )) != NULL )
for (loop; loop <= 10000000 ; loop++)
{

fprintf(fp,"%u\ n",fib(10));
}
fclose (fp);
return 0;
}

unsigned int fib (int n)
{ if (n != 1 )
return n * fib(n-1);
else
return 1;
}
and he did the something in C#
and then we all have the same laptop..DELL Inspiron 6000.

I ran my program, I took 18 seconds to get done..his program took 7
seconds..Wow

and then I asked him to run my program in his laptop..it's all the
same ..but I wanted to...I ran it...gave me the same time..

How come ..?!

Next day, I tried some Optimization

and developed the loop and wrote something like this

for (loop; loop <= 1000000 ; loop++)
{
fprintf(fp,"%u\ n %u\n %u\n %u\n %u\n
",fib(10),fib(1 0),fib(10),fib( 10),fib(10));
fprintf(fp,"%u\ n %u\n %u\n %u\n %u\n
",fib(10),fib(1 0),fib(10),fib( 10),fib(10));
}

But his program still faster than mine..

then, I tried the program under Slackware 12....it took 3.8 Seconds to
get done..Wow, I won the Challenge..

anyway, he want me to beat him under windows XP...Please guys help me
out..
Dec 12 '07
41 2708
c wrote:
On Dec 13, 2:51 am, Francine.Ne...@ googlemail.com wrote:
The answer to your question is 42.

What do you mean by 42..please give me more details..
<http://en.wikipedia.org/wiki/Answer_...se%2C_and_Ever
ything>

Brian
Dec 13 '07 #11
c wrote:
>
On Dec 13, 3:07 am, pete <pfil...@mindsp ring.comwrote:
My first guess is that fprintf is your slowest dog.
The second most obvious improvement would be to
remove recursion from your fib function.

Your program runs in 19 cursor blinks on my machine.
My program, new.c, runs in 11 cursor blinks.
thanks pete...
But I gotta use recursion..It's not fair..My friend uses recursion in
his program, the program that he wrote in C#..So I have to :-)
otherwise, I am cheating.
I put the recursion back in and timed it again.
It's still just as fast.
Why didn't you try that first yourself?

/* BEGIN new.c */

#include <stdio.h>
#include <limits.h>

long unsigned fib(int n);
void lutoa(long unsigned n, char *s);

int main(void)
{
FILE *fp;
long unsigned loop = 10000000;
char lutoa_buff[(sizeof(long) * CHAR_BIT ) / 3 + 1];

if ((fp = fopen("log.txt" , "w")) != NULL) {
do {
lutoa(fib(10), lutoa_buff);
fputs(lutoa_buf f, fp);
putc('\n', fp);
} while (--loop != 0);
fclose (fp);
}
return 0;
}

long unsigned fib(int n)
{
return n != 1 ? n * fib(n - 1) : 1;
}

void lutoa(long unsigned n, char *s)
{
long unsigned tenth;
char *p, swap;

p = s;
tenth = n;
do {
tenth /= 10;
*p++ = (char)(n - 10 * tenth + '0');
n = tenth;
} while (tenth != 0);
*p-- = '\0';
while (p s) {
swap = *s;
*s++ = *p;
*p-- = swap;
}
}

/* END new.c */
--
pete
Dec 13 '07 #12
c
On Dec 13, 3:43 am, pete <pfil...@mindsp ring.comwrote:
c wrote:
On Dec 13, 3:07 am, pete <pfil...@mindsp ring.comwrote:
My first guess is that fprintf is your slowest dog.
The second most obvious improvement would be to
remove recursion from your fib function.
Your program runs in 19 cursor blinks on my machine.
My program, new.c, runs in 11 cursor blinks.
thanks pete...
But I gotta use recursion..It's not fair..My friend uses recursion in
his program, the program that he wrote in C#..So I have to :-)
otherwise, I am cheating.

I put the recursion back in and timed it again.
It's still just as fast.
Why didn't you try that first yourself?

/* BEGIN new.c */

#include <stdio.h>
#include <limits.h>

long unsigned fib(int n);
void lutoa(long unsigned n, char *s);

int main(void)
{
FILE *fp;
long unsigned loop = 10000000;
char lutoa_buff[(sizeof(long) * CHAR_BIT ) / 3 + 1];

if ((fp = fopen("log.txt" , "w")) != NULL) {
do {
lutoa(fib(10), lutoa_buff);
fputs(lutoa_buf f, fp);
putc('\n', fp);
} while (--loop != 0);
fclose (fp);
}
return 0;

}

long unsigned fib(int n)
{
return n != 1 ? n * fib(n - 1) : 1;

}

void lutoa(long unsigned n, char *s)
{
long unsigned tenth;
char *p, swap;

p = s;
tenth = n;
do {
tenth /= 10;
*p++ = (char)(n - 10 * tenth + '0');
n = tenth;
} while (tenth != 0);
*p-- = '\0';
while (p s) {
swap = *s;
*s++ = *p;
*p-- = swap;
}

}

/* END new.c */

--
pete
Thank you very much, that's very sweet of you.
Dec 13 '07 #13
c
On Dec 13, 3:46 am, "Default User" <defaultuse...@ yahoo.comwrote:
c wrote:
On Dec 13, 2:51 am, Francine.Ne...@ googlemail.com wrote:
The answer to your question is 42.
What do you mean by 42..please give me more details..

<http://en.wikipedia.org/wiki/Answer_...se%2C_and_Ever
ything>

Brian
still don't know that do you guys mean by 42!!
!
!!
!!!
Dec 13 '07 #14
c wrote:
Hi every one,

Me and my Cousin were talking about C and C#, I love C and he loves
C#..and were talking C is ...blah blah...C# is Blah Blah ...etc

and then we decided to write a program that will calculate the
factorial of 10, 10 millions time and print the reusult in a file with
the name log.txt.
Methinks, you are not really measuring program speed, but I/O performance.

You was printing '3628800' 10 million times, that's only 7 bytes per I/O.

In C, try using fwrite() instead, and issue only one I/O per 4 kb, even
better should be one I/O per 64 kb. If doing that, I guess you drop
below 2 seconds on XP.

--
Tor <bw****@wvtqvm. vw | tr i-za-h a-z>
Dec 13 '07 #15
On Dec 13, 12:27 am, c <alcon...@gmail .comwrote:
c wrote:
Hi every one,
Me and my Cousin were talking about C and C#, I love C and he loves
C#..and were talking C is ...blah blah...C# is Blah Blah ...etc
<snip>

My friend uses recursion in
his program, the program that he wrote in C#..So I have to :-)
otherwise, I am cheating.
Hi c,

At the risk of starting yet another flame war on topicality... This
is all OT here, and you'd be better asking...mmm, I'm really not sure
actually. A windows comp group, maybe.

Have you checked the compiler settings you used when you compiled on
XP? (Richard Tobin mentioned this above, not sure if you spotted it.)

The fib() function you list (which, as others have said, should
probably be called fact()!) is an excellent candidate for
optimisation. Google for "tail recursion". If you turn up the
optimisation on your compiler then this might kick in and help a bit.

But I think that might be cheating too. AFAIK, the current C#
compiler doesn't use this optimisation. (The CLR supports it, but the
C# compiler doesn't yet emit it.) So I don't think your cousin's
program benefits from this. (Don't take my word as gospel.)

But as others have stated, it actually looks like it's the IO that's
being compared at the moment. I guess you're really comparing your c
standard lib implementation against the CLR, in one particular use
case.

Which is interesting, but probably not what you and your cousin set
out to compare. Maybe you and your cousin could come up with a range
of other tests - like purely compute-bound (crunch some matrices or
calculate some primes) or IO-bound (copy some files).

Doug
Dec 13 '07 #16
c wrote:
Hi every one,

Me and my Cousin were talking about C and C#, I love C and he loves
C#..and were talking C is ...blah blah...C# is Blah Blah ...etc

and then we all have the same laptop..DELL Inspiron 6000.

I ran my program, I took 18 seconds to get done..his program took 7
seconds..Wow
Must be down to your compiler or options, your code ran in 3 seconds on
my laptop (Dell M60, same CPU as the Inspiron 6000) and 1 second on my
desktop...

--
Ian Collins.
Dec 13 '07 #17
On Dec 12, 6:23 pm, c <alcon...@gmail .comwrote:
Hi every one,

Me and my Cousin were talking about C and C#, I love C and he loves
C#..and were talking C is ...blah blah...C# is Blah Blah ...etc

and then we decided to write a program that will calculate the
factorial of 10, 10 millions time and print the reusult in a file with
the name log.txt..
[ code elided ]

The two compilers you mentioned don't do much code optimization. On
the other hand, the MS C# compiler has a huge investment in the latest
technologies. If you use, say, Visual C++ 2005 Express Edition (which
I mention only because it's freely downloadable) and highest
optimization settings, the difference ought to be much smaller. Which
will be faster will depend on unpredictable details. For example,
some very aggressive optimizers will inline-expand a recursive
function in nested fashion a few times a la loop unrolling. This can
lead to very big speedups for codes like yours. Don't know if C# does
that. I don't think VC++ EE does.
Dec 13 '07 #18
On Dec 12, 4:05 pm, c <alcon...@gmail .comwrote:
On Dec 13, 2:54 am, user923005 <dcor...@connx. comwrote:


On Dec 12, 3:23 pm, c <alcon...@gmail .comwrote:
Hi every one,
Me and my Cousin were talking about C and C#, I love C and he loves
C#..and were talking C is ...blah blah...C# is Blah Blah ...etc
and then we decided to write a program that will calculate the
factorial of 10, 10 millions time and print the reusult in a file with
the name log.txt..
I wrote something like this
#include <stdio.h>
unsigned int fib (int n);
int main()
{
FILE *fp;
unsigned int loop =1 ;
if ( (fp = fopen( "log.txt", "a" )) != NULL )
for (loop; loop <= 10000000 ; loop++)
{
fprintf(fp,"%u\ n",fib(10));
}
fclose (fp);
return 0;
}
unsigned int fib (int n)
{ if (n != 1 )
return n * fib(n-1);
else
return 1;
}
and he did the something in C#
and then we all have the same laptop..DELL Inspiron 6000.
I ran my program, I took 18 seconds to get done..his program took 7
seconds..Wow
and then I asked him to run my program in his laptop..it's all the
same ..but I wanted to...I ran it...gave me the same time..
How come ..?!
Next day, I tried some Optimization
and developed the loop and wrote something like this
for (loop; loop <= 1000000 ; loop++)
{
fprintf(fp,"%u\ n %u\n %u\n %u\n %u\n
",fib(10),fib(1 0),fib(10),fib( 10),fib(10));
fprintf(fp,"%u\ n %u\n %u\n %u\n %u\n
",fib(10),fib(1 0),fib(10),fib( 10),fib(10));
}
But his program still faster than mine..
then, I tried the program under Slackware 12....it took 3.8 Seconds to
get done..Wow, I won the Challenge..
anyway, he want me to beat him under windows XP...Please guys help me
out..
The recursive factorial function will be a lot slower than an
iterative one.
But the lion's share of the time is going to be in writing out the
text file.
It occupies 160 MB on my machine. It appears that your friend has a
faster disk than you do.
This might be marginally faster:
#include <stdio.h>
unsigned fact(unsigned n)
{
unsigned result = 1;
while (n-- 1)
result *= n;
return result;
}
int main()
{
FILE *fp;
unsigned loop;
if ((fp = fopen("log.txt" , "a")) != NULL) {
setvbuf(fp, NULL, _IOFBF, 16000);
for (loop=1; loop <= 10000000; loop++) {
fprintf(fp, "%u\n", fact(10));
}
fclose(fp);
}
return 0;
}
This program executes in less than one second on my machine (showing
that the time is almost exclusively I/O):
#include <stdio.h>
unsigned fact(unsigned n)
{
unsigned result = 1;
while (n-- 1)
result *= n;
return result;
}
int main()
{
FILE *fp;
unsigned loop;
double sum = 0;
if ((fp = fopen("log.txt" , "a")) != NULL) {
setvbuf(fp, NULL, _IOFBF, 16000);
for (loop=1; loop <= 10000000; loop++) {
sum += fact(10);
}
printf("sum was %f\n", sum);
fclose(fp);
}
return 0;}
/*
C:\tmp>foo
sum was 3628800000000.0 00000
*/

Thanks sir for you reply..
you mentioned "It appears that your friend has a
faster disk than you do"
We both have the same laptop..same model..anyway, I tested my program
in his laptop just in case..
anyway, I compiled the code you posted..its save a 0-byte text file on
machine..
I will try with another compiler..I'll get back to you..
If your disk drives are the same, that indicates that the buffered I/O
of C# is superior to the buffered I/O of C.

You must have compiled the second program, which does not write
anything to disk.
The first program writes a 160 MB file.

Here is a very cheesy alternative:

#include <stdio.h>
#include <string.h>
#include <errno.h>

unsigned fact(unsigned n)
{
unsigned result = 1;
while (n-- 1)
result *= n;
return result;
}

static char absurd_buffer[160000000];

int main(void)
{
FILE *fp;
unsigned loop;
if ((fp = fopen("log.txt" , "w")) != NULL) {

if (setvbuf(fp, absurd_buffer, _IOFBF, sizeof absurd_buffer) !
= 0) {
int e = errno;
puts(strerror(e ));
printf("Incorre ct type or size of buffer for log.txt.
Value of errno is %d.\n", e);
}
for (loop = 1; loop <= 10000000; loop++) {
fprintf(fp, "%u\n", fact(10));
}
fclose(fp);
}
return 0;
}

Dec 13 '07 #19
c wrote:
On Dec 13, 3:46 am, "Default User" <defaultuse...@ yahoo.comwrote:
>c wrote:
>>On Dec 13, 2:51 am, Francine.Ne...@ googlemail.com wrote:
The answer to your question is 42.
What do you mean by 42..please give me more details..
<http://en.wikipedia.org/wiki/Answer_...se%2C_and_Ever
ything>

Brian

still don't know that do you guys mean by 42!!
If you followed up that wikipedia link, you should know that '42' is
meant as a nonsense answer to a question that hasn't been well-thought out.
Dec 13 '07 #20

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2767
by: =?Utf-8?B?QnJvbmlzbGF2?= | last post by:
I need to run more then 1 instance of the same program but also I need to know which instance is running. In C++ code was: int nInstance = 0; char szAppName; m_dwMutexReturn = ERROR_ALREADY_EXISTS; while (( m_dwMutexReturn == ERROR_ALREADY_EXISTS ) && ( nInstance < MAXINSTANCES ))
0
1359
by: John Scheldroup | last post by:
Source: Article Mixing C and C++ Code in the Same Program By Stephen Clamage, Sun Microsystems, Sun ONE Studio Solaris Tools Development Engineering http://developers.sun.com/solaris/articles/mixing.html
1
1272
by: poijoy | last post by:
I need to use two forms in one program for another school project. The textbook is annoyingly vague as to how to do this. It states that I should use the line Dim secondForm as New Form2() but it doesn't say anything enlightening after that. The program is a supposed to get information about travel expenses, sum it up, and display the information in a separate window in a listbox. I get how to add items to a list box. I get how to do...
0
9684
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9530
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10459
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10236
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9055
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7552
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6793
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.