473,832 Members | 2,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C# v. C++ Performance

I read that C#'s JIT compiler produces very efficient
machine code. However, I've found when performing
extensive numerical calculations that C# is less than a
fourth the speed of C++. I give code examples below. Both
C# and C++ were compiled as release builds with default
optimisation on (C++ has /Ob1 set in addition to default
optimizations). I suspected the relatively poor C#
performance was due to using managed memory, but
adding 'unsafe' to relevant classes and methods makes
little or no difference.

I'd appreciate advice on how I can bring the C#
performance close to that of C++, or an acknowledgement
that for the code samples below, C# is fundamentally
several times slower than (unmanaged) C++.

C++ Code:

double total = 0.0;

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (long i = 0; i < 100000000; i++)
{
total += i/999999.0;
double disc = total*total + i;
double root = (total + disc)/
(200000.0*(i + 1));
total -= root;
}
}

C# Code:

double total = 0.0;

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (long i = 0; i <
100000000; i++)
{
total +=
i/999999.0;
double disc =
total*total + i;
double root =
(total + disc)/(200000.0*(i + 1));
total -= root;
}
}
Nov 15 '05 #1
14 7246
Longs 32bit in native code (C/C++) but are 64 bit in managed code, change
.... for (long i = 0; i < > 100000000; i++) in you C# code into for (int
i=...

Willy.
"Nigel" <ni***@nigelwil son.evesham.net .remove_this> wrote in message
news:0a******** *************** *****@phx.gbl.. .
I read that C#'s JIT compiler produces very efficient
machine code. However, I've found when performing
extensive numerical calculations that C# is less than a
fourth the speed of C++. I give code examples below. Both
C# and C++ were compiled as release builds with default
optimisation on (C++ has /Ob1 set in addition to default
optimizations). I suspected the relatively poor C#
performance was due to using managed memory, but
adding 'unsafe' to relevant classes and methods makes
little or no difference.

I'd appreciate advice on how I can bring the C#
performance close to that of C++, or an acknowledgement
that for the code samples below, C# is fundamentally
several times slower than (unmanaged) C++.

C++ Code:

double total = 0.0;

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (long i = 0; i < 100000000; i++)
{
total += i/999999.0;
double disc = total*total + i;
double root = (total + disc)/
(200000.0*(i + 1));
total -= root;
}
}

C# Code:

double total = 0.0;

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (long i = 0; i <
100000000; i++)
{
total +=
i/999999.0;
double disc =
total*total + i;
double root =
(total + disc)/(200000.0*(i + 1));
total -= root;
}
}

Nov 15 '05 #2
I can't offer much more than a comment at the moment, but in my experience
numerical calculations are precisely the area where C# should be on equal
ground with C++. I've had very good results with C# for intense numerical
computations. If, for some reason, you end up finding out the C# won't do
the job (I'd be surprised), you could always put the most performance
senstive code in C or C++ (even in an unmanaged DLL) and call it from C#.
I've done that before with very good results (only because some code was
already in C). The performance using PInvoke was really good.
HTH

"Nigel" <ni***@nigelwil son.evesham.net .remove_this> wrote in message
news:0a******** *************** *****@phx.gbl.. .
I read that C#'s JIT compiler produces very efficient
machine code. However, I've found when performing
extensive numerical calculations that C# is less than a
fourth the speed of C++. I give code examples below. Both
C# and C++ were compiled as release builds with default
optimisation on (C++ has /Ob1 set in addition to default
optimizations). I suspected the relatively poor C#
performance was due to using managed memory, but
adding 'unsafe' to relevant classes and methods makes
little or no difference.

I'd appreciate advice on how I can bring the C#
performance close to that of C++, or an acknowledgement
that for the code samples below, C# is fundamentally
several times slower than (unmanaged) C++.

C++ Code:

double total = 0.0;

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (long i = 0; i < 100000000; i++)
{
total += i/999999.0;
double disc = total*total + i;
double root = (total + disc)/
(200000.0*(i + 1));
total -= root;
}
}

C# Code:

double total = 0.0;

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (long i = 0; i <
100000000; i++)
{
total +=
i/999999.0;
double disc =
total*total + i;
double root =
(total + disc)/(200000.0*(i + 1));
total -= root;
}
}

Nov 15 '05 #3
Nigel <ni***@nigelwil son.evesham.net .remove_this> wrote:
I read that C#'s JIT compiler produces very efficient
machine code.
C# doesn't have a JIT compiler. .NET has a JIT compiler. You need to be
very clear on where the boundaries are.
However, I've found when performing
extensive numerical calculations that C# is less than a
fourth the speed of C++. I give code examples below. Both
C# and C++ were compiled as release builds with default
optimisation on (C++ has /Ob1 set in addition to default
optimizations). I suspected the relatively poor C#
performance was due to using managed memory, but
adding 'unsafe' to relevant classes and methods makes
little or no difference.

I'd appreciate advice on how I can bring the C#
performance close to that of C++, or an acknowledgement
that for the code samples below, C# is fundamentally
several times slower than (unmanaged) C++.


C# itself is a language, not an implementation. However, assuming that
weren't actually a problem... "fundamenta lly" is a very strange word to
use here - there are certain benchmarks that could no doubt be produced
where C++ ends up slower than C# - how can two languages themselves
each be "fundamenta lly" slower than the other?

There are certain situations where C++ will be faster than C#, and vice
versa.

Now, let's look at your case in point. Here are the raw numbers from my
laptop - not the ideal testing scenario, but not a bad starting point:

First run:
C++: 27s
C#: 70s

Already this is less than the factor of four you were quoting - indeed,
it's not even three times as slow. Still, let's see what we can do...

There looks to be a lot of casting from long to double here. Changing
the C# code to:

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (double i = 0; i < 100000000d; i+=1.0d)
{
total += i/999999.0;
double disc = total*total + i;
double root = (total + disc)/(200000.0*(i + 1.0d));
total -= root;
}
}

the execution time for C# goes down to just 18 seconds! (The results
appear to be the same, and I can't see why it wouldn't be a perfectly
valid optimisation to perform - the only possible loss of precision
would be where converting (i+1) to a double would have a different
result to adding 1.0 to the double value of i. I've verified that
doesn't occur anywhere in the range 0-100000000; in actual code you
might want to check whether or not it could be a problem.

Changing the C++ code in a similar way doesn't appear to help it.

So, according to the above, would you acknowledge that "C# is
fundamentally significantly faster than (unmanaged) C++" or would you
acknowledge that single benchmarks aren't necessarily a good indication
of an entire platform?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #4
Thats a first run, try a second run for a warm start.
"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Nigel <ni***@nigelwil son.evesham.net .remove_this> wrote:
I read that C#'s JIT compiler produces very efficient
machine code.


C# doesn't have a JIT compiler. .NET has a JIT compiler. You need to be
very clear on where the boundaries are.
However, I've found when performing
extensive numerical calculations that C# is less than a
fourth the speed of C++. I give code examples below. Both
C# and C++ were compiled as release builds with default
optimisation on (C++ has /Ob1 set in addition to default
optimizations). I suspected the relatively poor C#
performance was due to using managed memory, but
adding 'unsafe' to relevant classes and methods makes
little or no difference.

I'd appreciate advice on how I can bring the C#
performance close to that of C++, or an acknowledgement
that for the code samples below, C# is fundamentally
several times slower than (unmanaged) C++.


C# itself is a language, not an implementation. However, assuming that
weren't actually a problem... "fundamenta lly" is a very strange word to
use here - there are certain benchmarks that could no doubt be produced
where C++ ends up slower than C# - how can two languages themselves
each be "fundamenta lly" slower than the other?

There are certain situations where C++ will be faster than C#, and vice
versa.

Now, let's look at your case in point. Here are the raw numbers from my
laptop - not the ideal testing scenario, but not a bad starting point:

First run:
C++: 27s
C#: 70s

Already this is less than the factor of four you were quoting - indeed,
it's not even three times as slow. Still, let's see what we can do...

There looks to be a lot of casting from long to double here. Changing
the C# code to:

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (double i = 0; i < 100000000d; i+=1.0d)
{
total += i/999999.0;
double disc = total*total + i;
double root = (total + disc)/(200000.0*(i + 1.0d));
total -= root;
}
}

the execution time for C# goes down to just 18 seconds! (The results
appear to be the same, and I can't see why it wouldn't be a perfectly
valid optimisation to perform - the only possible loss of precision
would be where converting (i+1) to a double would have a different
result to adding 1.0 to the double value of i. I've verified that
doesn't occur anywhere in the range 0-100000000; in actual code you
might want to check whether or not it could be a problem.

Changing the C++ code in a similar way doesn't appear to help it.

So, according to the above, would you acknowledge that "C# is
fundamentally significantly faster than (unmanaged) C++" or would you
acknowledge that single benchmarks aren't necessarily a good indication
of an entire platform?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #5
<di********@dis cussion.microso ft.com> wrote:
Thats a first run, try a second run for a warm start.


I ran the code several times, actually (both versions). For the .NET
version, I only timed the code between the start of the method
executing and the end - the only JIT compilation time required would be
for Console.WriteLi ne and DateTime.Now. Unlike Java, .NET only JITs
once so you don't need to run the same method many times in order to
get the code to run as fast as possible - aside from the time spent to
JIT in the first place, it's running as fast as it's going to by the
time it's running the first time.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #6
Jon,

The main problem with OP's code is the for loop using longs, which are as
you know 64 bit in .NET and 32 bit in native code.
Quite a diffrerence if you are adding/comparing a 32 bit vs. a 64 bit entity
on a 32 bit CPU....( and this 100.000.000 times)

Using for(int i=0; i<...
Both C++ and C# took the same time to run to completion.

Willy.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
Nigel <ni***@nigelwil son.evesham.net .remove_this> wrote:
I read that C#'s JIT compiler produces very efficient
machine code.


C# doesn't have a JIT compiler. .NET has a JIT compiler. You need to be
very clear on where the boundaries are.
However, I've found when performing
extensive numerical calculations that C# is less than a
fourth the speed of C++. I give code examples below. Both
C# and C++ were compiled as release builds with default
optimisation on (C++ has /Ob1 set in addition to default
optimizations). I suspected the relatively poor C#
performance was due to using managed memory, but
adding 'unsafe' to relevant classes and methods makes
little or no difference.

I'd appreciate advice on how I can bring the C#
performance close to that of C++, or an acknowledgement
that for the code samples below, C# is fundamentally
several times slower than (unmanaged) C++.


C# itself is a language, not an implementation. However, assuming that
weren't actually a problem... "fundamenta lly" is a very strange word to
use here - there are certain benchmarks that could no doubt be produced
where C++ ends up slower than C# - how can two languages themselves
each be "fundamenta lly" slower than the other?

There are certain situations where C++ will be faster than C#, and vice
versa.

Now, let's look at your case in point. Here are the raw numbers from my
laptop - not the ideal testing scenario, but not a bad starting point:

First run:
C++: 27s
C#: 70s

Already this is less than the factor of four you were quoting - indeed,
it's not even three times as slow. Still, let's see what we can do...

There looks to be a lot of casting from long to double here. Changing
the C# code to:

for (int rep = 0; rep < 5; rep++)
{
total /= 1000.0;

for (double i = 0; i < 100000000d; i+=1.0d)
{
total += i/999999.0;
double disc = total*total + i;
double root = (total + disc)/(200000.0*(i + 1.0d));
total -= root;
}
}

the execution time for C# goes down to just 18 seconds! (The results
appear to be the same, and I can't see why it wouldn't be a perfectly
valid optimisation to perform - the only possible loss of precision
would be where converting (i+1) to a double would have a different
result to adding 1.0 to the double value of i. I've verified that
doesn't occur anywhere in the range 0-100000000; in actual code you
might want to check whether or not it could be a problem.

Changing the C++ code in a similar way doesn't appear to help it.

So, according to the above, would you acknowledge that "C# is
fundamentally significantly faster than (unmanaged) C++" or would you
acknowledge that single benchmarks aren't necessarily a good indication
of an entire platform?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #7
Willy Denoyette [MVP] <wi************ *@pandora.be> wrote:
The main problem with OP's code is the for loop using longs, which are as
you know 64 bit in .NET and 32 bit in native code.
Quite a diffrerence if you are adding/comparing a 32 bit vs. a 64 bit entity
on a 32 bit CPU....( and this 100.000.000 times)
Yes - I even thought about that as I was originally responding, but had
a brain fart and didn't end up picking it up properly.
Using for(int i=0; i<...
Both C++ and C# took the same time to run to completion.


Actually, when I ran it, C# had the edge using ints on my box - 20s vs
27s. However, using a double for the loop counter is even faster (18s).

Interestingly, I thought I'd get rid of the duplicate (i+1) by having
another variable which would act as the next value of i and the amount
to multiply by 200000 - but that decreased performance. I haven't
managed to increase performance beyond that 18s mark.

I've just tried with /O2 on the C++ version, and that actually runs in
about 15s, so there's still room for improvement in the CLR, but it's
still very impressive, IMO.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #8
On Mon, 8 Dec 2003 23:53:34 -0000, Jon Skeet [C# MVP]
<sk***@pobox.co m> wrote:
So, according to the above, would you acknowledge that "C# is
fundamentall y significantly faster than (unmanaged) C++" or would you
acknowledge that single benchmarks aren't necessarily a good indication
of an entire platform?


Actually, C++ is infinitely faster than C# because VC++ 7.1 with the
/Ox switch optimized away the entire loop!

After inserting a "return (int) total;" statement at the end so that
the loop was actually executed, optimized builds for both languages
performed at about the same speed on my system (~12 seconds), with C++
coming out slightly ahead (let's say 11.5 seconds). The C# version
was of course fixed to use an int counter instead of a long counter.

That was one remarkably poor "benchmark" that the OP used. Isn't
there some "Benchmarks for Dummies" book that could be recommended in
such cases? If you have lots of time you might want to add a
benchmarking section to your page, seeing how you already took care of
the floating-point and Unicode questions. ;-)
--
http://www.kynosarges.de
Nov 15 '05 #9
How does the JIT handle dynamic code?

What if I change a class during runtime (it can be done)

Self modifying code for example, GAs.

"Jon Skeet [C# MVP]" <sk***@pobox.co m> wrote in message
news:MP******** *************** *@msnews.micros oft.com...
<di********@dis cussion.microso ft.com> wrote:
Thats a first run, try a second run for a warm start.


I ran the code several times, actually (both versions). For the .NET
version, I only timed the code between the start of the method
executing and the end - the only JIT compilation time required would be
for Console.WriteLi ne and DateTime.Now. Unlike Java, .NET only JITs
once so you don't need to run the same method many times in order to
get the code to run as fast as possible - aside from the time spent to
JIT in the first place, it's running as fast as it's going to by the
time it's running the first time.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too

Nov 15 '05 #10

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

Similar topics

25
3499
by: Brian Patterson | last post by:
I have noticed in the book of words that hasattr works by calling getattr and raising an exception if no such attribute exists. If I need the value in any case, am I better off using getattr within a try statement myself, or is there some clever implementation enhancement which makes this a bad idea? i.e. should I prefer: if hasattr(self,"datum"): datum=getattr("datum") else: datum=None
12
17312
by: Fred | last post by:
Has anyone a link or any information comparing c and c++ as far as execution speed is concerned? Signal Processing algorithms would be welcome... Thanks Fred
12
8356
by: serge | last post by:
I have an SP that is big, huge, 700-800 lines. I am not an expert but I need to figure out every possible way that I can improve the performance speed of this SP. In the next couple of weeks I will work on preparing SQL statements that will create the tables, insert sample record and run the SP. I would hope people will look at my SP and give me any hints on how I can better write the SP.
6
2327
by: teedilo | last post by:
We have an application with a SQL Server 2000 back end that is fairly database intensive -- lots of fairly frequent queries, inserts, updates -- the gamut. The application does not make use of performance hogs like cursors, but I know there are lots of ways the application could be made more efficient database-wise. The server code is running VB6 of all things, using COM+ database interfaces. There are some clustered and non-clustered...
5
4010
by: Scott | last post by:
I have a customer that had developed an Access97 application to track their business information. The application grew significantly and they used the Upsizing Wizard to move the tables to SQL 2000. Of course there were no modifications made to the queries and they noticed significant performance issues. They recently upgraded the application to Access XP expecting the newer version to provide performance benefits and now queries take...
115
7670
by: Mark Shelor | last post by:
I've encountered a troublesome inconsistency in the C-language Perl extension I've written for CPAN (Digest::SHA). The problem involves the use of a static array within a performance-critical transform function. When compiling under gcc on my big-endian PowerPC (Mac OS X), declaring this array as "static" DECREASES the transform throughput by around 5%. However, declaring it as "static" on gcc/Linux/Intel INCREASES the throughput by...
13
2774
by: bjarne | last post by:
Willy Denoyette wrote; > ... it > was not the intention of StrousTrup to the achieve the level of efficiency > of C when he invented C++, ... Ahmmm. It was my aim to match the performance of C and I achieved that aim very early on. See, for example "The Design and Evolution of C++". -- Bjarne Stroustrup; http://www.research.att.com/~bs
13
4157
by: Bern McCarty | last post by:
I have run an experiment to try to learn some things about floating point performance in managed C++. I am using Visual Studio 2003. I was hoping to get a feel for whether or not it would make sense to punch out from managed code to native code (I was using IJW) in order to do some amount of floating point work and, if so, what that certain amount of floating point work was approximately. To attempt to do this I made a program that...
7
2582
by: Michael D. Ober | last post by:
When calling Enqueue, the internal array may need to be reallocated. My question is by how much? In the old MFC array classes, you could tell MFC how many additional elements to add to the array when it needed to reallocate, which greatly boosted performance relative to adding 1 element at a time. Thanks, Mike Ober.
1
2461
by: jvn | last post by:
I am experiencing a particular problem with performance counters. I have created a set of classes, that uses System.Diagnostics.PerformanceCounter to increment custom performance counters (using .Net 2.0) The performance counter categories have been successfully created. When the set of classes are used by a WinForm test harness application, they function as expected, and the performance counters can be seen to be updated by using the...
0
9794
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
10780
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...
1
10539
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
10212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7753
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
6951
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
5623
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...
1
4420
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
3
3077
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.