943,901 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 2680
  • C++ RSS
Nov 2nd, 2008
0

C# faster than C++ ??

Expand Post »
Hey Everyone,

I'm doing a little test for a presentation I'm giving on Tuesday. I wanted to show the performance difference between VB2008, C# and C++.

To do this, I have three programs. Each program performs the Fibonacci sequence X times, and can either do it iteratively or recursively. As expected both C# and C++ blow VB away. However, my test between C# (with GUI) and C++ (command line) was a little surprising.

I did 40 Fibonacci numbers, both iteratively and recursively. The iterative tests show the same time to the millisecond almost. However, when doing the recursive test, C# completed the calculation in 3.8 seconds, while it took C++ about 12.1 seconds. Is this expected? I would have thought C++, especially with it being command line, would have outperformed C#?

Here are my codes... maybe you can see an 'unfairness' that might help clear things up. Or am I wrong in thinking C++ is quicker than C#?

C++ Code:
c++ Syntax (Toggle Plain Text)
  1. #include <iostream>
  2. #include <ctime>
  3. #include <stdio.h>
  4. #include <time.h>
  5.  
  6. using namespace std ;
  7.  
  8. unsigned long first = 0;
  9. unsigned long second = 1 ;
  10. unsigned long result ;
  11.  
  12. time_t start, end ;
  13. double total ;
  14.  
  15. int x ;
  16. int ans ;
  17.  
  18. unsigned long fib( int n ) ;
  19.  
  20. int main()
  21. {
  22. cout << endl << " Fibonacci Sequence Test -> C++ " << endl ;
  23. cout << "_____________________________________" << endl ;
  24.  
  25.  
  26. cout << endl << endl << endl ;
  27.  
  28. cout << "Number of iterations to calculate: " ;
  29. cin >> x ;
  30. cout << endl << endl ;
  31.  
  32. cout << "1. Iterative" << endl ;
  33. cout << "2. Recursive" << endl ;
  34. cout << "Select method: " << endl ;
  35. cin >> ans ;
  36. cout << endl ;
  37.  
  38. if ( ans == 1 )
  39. {
  40. start = clock() ;
  41. for ( int i = 0; i <= x ; i++ )
  42. {
  43. //cout << result << endl ;
  44. first = second ;
  45. second = result ;
  46. result = first + second ;
  47. }
  48. end = clock() ;
  49. total = (end - start) * .001 ;
  50.  
  51. cout << "Result: " << endl ;
  52. cout.precision(10) ;
  53. cout << "Total Time: " << total << endl ;
  54. }
  55. else if ( ans == 2 )
  56. {
  57. start = clock() ;
  58. result = fib(x) ;
  59. end = clock() ;
  60. total = (end - start) * .001 ;
  61.  
  62. cout << "Result: " << result << endl ;
  63. cout.precision(10) ;
  64. cout << "Total Time: " << total << endl ;
  65. }
  66.  
  67.  
  68. return 0 ;
  69. }
  70.  
  71. unsigned long fib( int n )
  72. {
  73. if (n <= 1)
  74. return n;
  75. else
  76. return fib(n-1)+fib(n-2);
  77. };

C# Code:
c# Syntax (Toggle Plain Text)
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Windows.Forms;
  9.  
  10. namespace FibCsharp
  11. {
  12.  
  13. public partial class Form1 : Form
  14. {
  15. double startTime;
  16. double endTime;
  17. double totalTime;
  18.  
  19. ulong first = 0;
  20. ulong second = 1;
  21. ulong result;
  22.  
  23. public Form1()
  24. {
  25. InitializeComponent();
  26. }
  27.  
  28. private void button1_Click(object sender, EventArgs e)
  29. {
  30. startTime = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second + DateTime.Now.Millisecond * .001;
  31. for (int i = 1; i <= 40; i++)
  32. {
  33. first = second;
  34. second = result;
  35. result = first + second;
  36. }
  37. endTime = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second + DateTime.Now.Millisecond * .001;
  38. totalTime = endTime - startTime;
  39.  
  40. label1.Text = Convert.ToDouble((totalTime)).ToString();
  41. textBox1.Text = result.ToString();
  42.  
  43.  
  44. }
  45.  
  46. private void button2_Click(object sender, EventArgs e)
  47. {
  48. startTime = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second + DateTime.Now.Millisecond * .001;
  49. result = fib(40);
  50. endTime = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second + DateTime.Now.Millisecond * .001;
  51. totalTime = (endTime - startTime);
  52.  
  53. label1.Text = Convert.ToDouble(totalTime).ToString();
  54. textBox1.Text = result.ToString();
  55. }
  56.  
  57. private ulong fib(ulong n)
  58. {
  59. if (n <= 1)
  60. return n;
  61. else
  62. return fib(n - 1) + fib(n - 2);
  63. }
  64. }
  65. }

Thanks
Similar Threads
Reputation Points: 817
Solved Threads: 32
Nearly a Posting Virtuoso
Duki is offline Offline
1,474 posts
since Jun 2006
Nov 2nd, 2008
0

Re: C# faster than C++ ??

Let me start by telling I am sort of a C# affictionado, with intrests in other languages. I am as surprised as you are. Even more because you did extra calculations in the C#version to time the thing.
Perhaps that's a problem. Try to use if possible the same class for timing. I don't know for C++ but in C# you have the Timer classes and the StopWatch class. An example of the use of StopWatch can be found in http://www.daniweb.com/code/snippet979.html.
Last edited by ddanbe; Nov 2nd, 2008 at 5:29 am. Reason: typo
Reputation Points: 2035
Solved Threads: 645
Senior Poster
ddanbe is offline Offline
3,740 posts
since Oct 2008
Nov 2nd, 2008
0

Re: C# faster than C++ ??

Oh and a tip :
Put your calculation in a for loop and perform it 1000000 times or so, that way the millisecs become less important.
Reputation Points: 2035
Solved Threads: 645
Senior Poster
ddanbe is offline Offline
3,740 posts
since Oct 2008
Nov 2nd, 2008
0

Re: C# faster than C++ ??

Is this really a fair comparison?

With C# you are using the CLR to indirectly use your OS and in C++ you are directly using the OS.

If you want this to be a fair comparison, try running the code using the CLR in C++ also.
Reputation Points: 392
Solved Threads: 108
Posting Shark
Alex Edwards is offline Offline
971 posts
since Jun 2008
Nov 2nd, 2008
0

Re: C# faster than C++ ??

So Alex, why is C++ slower? Without using the CLR it ought to be faster in my opinion.
Reputation Points: 2035
Solved Threads: 645
Senior Poster
ddanbe is offline Offline
3,740 posts
since Oct 2008
Nov 2nd, 2008
0

Re: C# faster than C++ ??

Firstly, your iterative versions aren't equivalent either: your iterate over a different interval in the loop.

As to the differences with the recursive versions, there are all sorts of possible explanations.

1) The way you're measuring time may have different granularity. The clock time is not infinite resolution - hence the tip by ddanbe to do a large number of calculations: for small duration calculations the error in the computed interval may be larger than the actual interval i.e. your timing results may be meaningless because you're not doing enough calculations.

2) The conversion of an interval (measured with two calls of clock()) is generally required to be divided by the value of the macro CLK_TCK to convert the interval to seconds. You're not doing that, so it's possible you've introduced a scaling factor on the computed times.

3) Compiler optimisation settings can have a significant effect: for example comparing a "Release" build with a "Debug" build in the other languages. "Release" builds tend to be optimised for speed, but "Debug" versions are not.

My guess, in your case, is a combination of all three.
Reputation Points: 193
Solved Threads: 32
Posting Whiz in Training
grumpier is offline Offline
206 posts
since Aug 2008
Nov 2nd, 2008
0

Re: C# faster than C++ ??

The VC++ now defines CLOCKS_PER_SEC (old CLK_TCK) macros as 1000, so there are no bad scaling in that case. However a real measured interval (i.e. VC++ RTL clock() precision) is about 15 milliseconds, so it's impossible to measure short intervals (iterative variant with clock() ticks <2 MICROseconds!).
For example, look at my snippet based on CPU Performance Clock Counter API (~1 microsecond precision):
http://www.daniweb.com/code/snippet916.html

Release version of this test runs 1.3 seconds on my CPU (debug version ~8 milliseconds). So I think recursive fib() code compiled with VC++ 2008 (and others) is faster than its C# incarnation, that's not the point.

Let's look at the "yellow press style" post header. The question: what's an object of this test? Is it C++, or C#? Obviously, answer negative. It's a test of 331,169,281 function calls. Of course, function call overheads is a very important parameter of - what? The language? No, it's a parameter of the language implementation (compiler+RTL).

It's a well-known fact: there are different compilers with different code generator qualities. Visual C++ is not a champion of C++ code optimisation.

So be careful with post titles ...
PS. It does not matter GUI or console environment used for function calls...
Last edited by ArkM; Nov 2nd, 2008 at 9:36 am.
Reputation Points: 1234
Solved Threads: 347
Postaholic
ArkM is offline Offline
2,001 posts
since Jul 2008
Nov 2nd, 2008
0

Re: C++ faster than C# ??

Here is my results for exactly your code in my Dell Inspiron 6400 laptop with Intel T2500 CPU and 2gb of Ram.

Results for VC++ 9.0

C++ Syntax (Toggle Plain Text)
  1. Fibonacci Sequence Test -> C++
  2. _____________________________________
  3.  
  4.  
  5.  
  6. Number of iterations to calculate: 40
  7.  
  8.  
  9. 1. Iterative
  10. 2. Recursive
  11. Select method:
  12. 2
  13.  
  14. Result: 102334155
  15. Total Time: 2.5
  16. Press any key to continue . . .



Results for Intel C++ compiler 10

C++ Syntax (Toggle Plain Text)
  1. Fibonacci Sequence Test -> C++
  2. _____________________________________
  3.  
  4.  
  5.  
  6. Number of iterations to calculate: 40
  7.  
  8.  
  9. 1. Iterative
  10. 2. Recursive
  11. Select method:
  12. 2
  13.  
  14. Result: 102334155
  15. Total Time: 2.391
  16. Press any key to continue . . .


And the result for C# 3 with .Net framework 3.5

C++ Syntax (Toggle Plain Text)
  1. Best Result for C#3 and .Net3.5 was 3.562


As you can see, in my computer test runs in C++ about %31 faster than C#.
Perhaps you forgot to enable optimization when compiling with C++.

PS the post title isn't appropriate.
Reputation Points: 14
Solved Threads: 0
Newbie Poster
rdjusr is offline Offline
3 posts
since Nov 2008
Nov 2nd, 2008
2

Re: C# faster than C++ ??

Just for the record, I wasn't trying to do yellow journalism or anything of that sort. If the title is offensive somehow, I apologize. Actually, I expected and was rooting for C++, so I assure you I wasn't trying to make false accusations. If a Mod would like to change the title to something more appropriate, feel free. Doesn't make a difference to me.


Thanks for the replies. I can understand datetime and clock() causing a timing difference in the iterative versions, but not the recursive; not that big anyways. The differences in time was about 8 seconds. I'm sure the different timing methods didn't cause an 8 second delay.

The iteration tests were the same to whoever said they weren't (as far as the number of iterations). I posted the last code I used, but I made sure to change it before my tests so that they were fair between the two.

I wasn't aware of an optimization capability. Thanks. Where do I access that? Also, is there the same sort of capability for C#?

thanks again for everyone's help
Last edited by Duki; Nov 2nd, 2008 at 7:45 pm.
Reputation Points: 817
Solved Threads: 32
Nearly a Posting Virtuoso
Duki is offline Offline
1,474 posts
since Jun 2006
Nov 3rd, 2008
0

Re: C# faster than C++ ??

By default all optimizations are enabled in the release configuration in visual studio standard edition and above. Remember that, all optimizations are off in default Debug configuration.

You can access optimization settings in project property page in the C/C++->Optimization and in the linker->optimization sections.

And if you are using cl command line, these switches are related to optimization:
/Od
/O1
/O2
/Ox
/Oi
and for linker:
/OPT:
Consult MSDN for more information.
Last edited by rdjusr; Nov 3rd, 2008 at 7:33 pm.
Reputation Points: 14
Solved Threads: 0
Newbie Poster
rdjusr is offline Offline
3 posts
since Nov 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Conversion error C2440
Next Thread in C++ Forum Timeline: Another beginner who needs to get one a foot in.





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC