473,796 Members | 2,560 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
On Dec 13, 4:52 am, user923005 <dcor...@connx. comwrote:
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;

}
I compiled you code with Borland C++ and used the option "optimize for
speed"
bcc32.exe -O2 fact.c

and Compiled the C# code, which uses recursion. yours doesn't

all on one Computer, the same Computer...all on his laptop..

guess what..his is faster, way faster...I tried all of the code posted
on this article...every single code you guys posted...he still
faster...and way faster...

but under Slackware..any code will be faster, even stupid code....
with recursion or with out..

Dec 13 '07 #21
c <al******@gmail .comwrites:
[...]
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;
}
[snip]

As others have mentioned, you don't actually seem to be measuring your
fib() (should be called fact() or factorial()) function.

On my system, your program ran in 4.98 seconds. When I changed the
line
fprintf(fp,"%u\ n",fib(10));
to
fprintf(fp, "%u\n", 3628800u);
it ran in 5.27 seconds.

I don't believe the apparent slowdown is significant; it's probably
with the margin of error of my measurement. But it suggests that the
performance of the program is dominated by writing 153 megabytes (!)
of output.

If you really want to measure the speed of the computations, don't
intersperse it with I/O.

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 13 '07 #22
Tor Rustad <to********@hot mail.comwrites:
c wrote:
>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.
I doubt it. Output using stdio is buffered; most of those fprintf
calls are just writing to memory. Probably the overhead of fprintf
processing the format string is significant; I just sped it up by a
factor of 3 or so by using fputs() rather than fprintf() (with a
constant string in both cases).

Actually, that could be an interesting exercise: find out where the
program is really spending its time. (Note that such an exercise
isn't necessarily topical here in comp.lang.c.)

--
Keith Thompson (The_Other_Keit h) <ks***@mib.or g>
Looking for software development work in the San Diego area.
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Dec 13 '07 #23
Richard Tobin wrote:
In article <da************ *************** *******@c4g2000 hsg.googlegroup s.com>,
c <al******@gmail .comwrote:
>unsigned int fib (int n)
{ if (n != 1 )
return n * fib(n-1);
else
return 1;
}

I think "fact" would be a better name for this function.
You can't trust people who tell fibs.
Dec 13 '07 #24
On 13 Des, 03:42, Keith Thompson <ks...@mib.orgw rote:
As others have mentioned, you don't actually seem to be measuring your
fib() (should be called fact() or factorial()) function.

On my system, your program ran in 4.98 seconds. When I changed the
line
fprintf(fp,"%u\ n",fib(10));
to
fprintf(fp, "%u\n", 3628800u);
it ran in 5.27 seconds.
Yeah, as expected, an IO bound problem this.
I don't believe the apparent slowdown is significant; it's probably
with the margin of error of my measurement. But it suggests that the
performance of the program is dominated by writing 153 megabytes (!)
of output.
Keith, may you explain how is writing 7 bytes 10 million times,
generating a 153 Mb file on your system?

Did you run the program twice? ;-)

--
Tor
Dec 13 '07 #25
On 13 Des, 03:46, Keith Thompson <ks...@mib.orgw rote:
Tor Rustad <tor_rus...@hot mail.comwrites:
c wrote:
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.

I doubt it. Output using stdio is buffered; most of those fprintf
calls are just writing to memory.
Well, I can check it, when getting back from work. After doing some
code changes,
I'm 99% sure my version will run below 2 seconds on my laptop, the
Fujitsu 2.5-inch
SATA HD there have specs for 150 MB/s! :)

Regarding 7 bytes fprintf(), odd plus odd is even, even plus odd is
odd. So
it goes 10 million times, that's at least 5 million non-optimal
memory
accesses...

Perhaps, the bottleneck on most systems is the disk-subsystem, but
the least we can do, is make sure that every IO is accessing
aligned memory, and change buffer from 7 bytes to something bigger
(e.g. 64 kb).

---
Tor
Dec 13 '07 #26
c schrieb:
unsigned int fib (int n)
{ if (n != 1 )
return n * fib(n-1);
else
return 1;
}
and he did the something in C#
1. Use the itarative variant, as was pointed out.
2. Mark the function "const"!

I wonder why nobody has pointed out #2 so far - probably because it's
not a language thing, but a compiler specification. When using gcc, it
will work, it might with other compilers as well. When optimization is
used it will make your program run like hell, as the factorial is only
calculated one single time. Kind of unfair, yes, but a cool
optimization. And you're comparing apples to oranges anyways, so...

Define/declare your function like this

#include <stdio.h>

unsigned fact(unsigned n) __attribute__(( const));

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

int main() {
int i;
for (i = 0; i < 1000000; i++) {
printf("%d\n", fact(10));
}
return 0;
}
Greetings,
Johannes

--
"Viele der Theorien der Mathematiker sind falsch und klar
Gotteslästerli ch. Ich vermute, dass diese falschen Theorien genau
deshalb so geliebt werden." -- Prophet und Visionär Hans Joss aka
HJP in de.sci.mathemat ik <47************ **********@news .sunrise.ch>
Dec 13 '07 #27
Johannes Bauer wrote:
c schrieb:
>unsigned int fib (int n)
{ if (n != 1 )
return n * fib(n-1);
else
return 1;
}
and he did the something in C#

1. Use the itarative variant, as was pointed out.
2. Mark the function "const"!

I wonder why nobody has pointed out #2 so far - probably because it's
not a language thing, but a compiler specification.
Exactly.
When using gcc, it
will work, it might with other compilers as well. When optimization is
used it will make your program run like hell,
Haven't various posters established that the time /of the program being
tested/ is dominated by /output/? Having fact-misnamed-fib take /zero
time/ won't help appreciably.

--
Chris "expanding head" Dollin

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England

Dec 13 '07 #28
On 12 Dec, 23:23, 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;
}
Since everything here is hard-wired, why not simply:

#include <stdio.h>

int main()
{
FILE *fp;
unsigned int loop =1 ;
if ( (fp = fopen( "log.txt", "a" )) != NULL )
for (loop; loop <= 10000000 ; loop++)
{
fprintf(fp,"362 8800\n");
}
fclose (fp);
return 0;
}

I betcha that's faster than the recursion...
Dec 13 '07 #29
On 2007-12-12, c <al******@gmail .comwrote:
I ran my program, I took 18 seconds to get done..his program
took 7 seconds..Wow
His program is probably buggy. Write another C program to verify
that his program's output is identical to yours.

--
Neil Cerutti
Any time I've taken the mound, it's always been the old Samson-and-Goliath
story written about me. --Randy Johnson
Dec 13 '07 #30

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,...
1
10182
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
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...
0
5445
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5577
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3734
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2928
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.