CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 15 of 15
  1. #1
    Join Date
    Mar 2008
    Posts
    161

    [RESOLVED] Isn't C++ Suppose to be faster than .NET?

    I have always heard that C++ was faster than C#.

    So I decided to do a test on which could count to 10000000 faster using a for loop.

    And amazingly C# does it much faster.

    For the test i made 2 really basic console applications. One in C# and one In C++.

    ChallengeCS.exe Source: C#
    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace CallengeCS
    {
        class Program
        {
            static void Main( string[ ] args )
            {
                for( int i = 0; i <= 10000000; i++ )
                {
                    Console.WriteLine ( i.ToString ( ) );     
                }
                Console.ReadLine ( );
            }
        }
    }
    And i also made sortof the same thing in C++.

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    	for (int i = 0; i <= 10000000; i++)
    	{
    		cout << i << endl;
    	}
    	cin.get();
    }
    Anyone know why C# is completing this faster?

    I made a video so you do not have to compile these yourselves.

    http://s287.photobucket.com/albums/l...rrent=Test.flv

    The one on the right is C#, the other is C++.

    Let me know what you think if you know why C# could be completing first?

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Isn't C++ Suppose to be faster than .NET?

    I think that's far too simplistic a program to really test relative speed. For one thing, writing to the screen will slow any program down considerably. An order of magnitude, at least. Usually more.

    One thing you might try is replacing the endl with a '\n', and just putting on endl at the end. Writing an endl flushes the output; there's typically no need to do that every line when you're looking for speed.

  3. #3
    Join Date
    Jul 2007
    Posts
    609

    Re: Isn't C++ Suppose to be faster than .NET?

    The optimization level can make a big difference too. Try -O3 when compiling your C++ program. I recently learned of that flag myself and could not believe the big difference.
    http://www.uovalor.com :: Free UO Server

  4. #4
    Join Date
    Mar 2008
    Posts
    161

    Re: Isn't C++ Suppose to be faster than .NET?

    Quote Originally Posted by Red Squirrel
    The optimization level can make a big difference too. Try -O3 when compiling your C++ program. I recently learned of that flag myself and could not believe the big difference.
    Eh, i am too new to this to know how to change my optimization level.

    Want to tell me how to change it?

  5. #5
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: Isn't C++ Suppose to be faster than .NET?

    Depends on the compiler. For gcc/g++, just put -O3 on the command line. For Visual Studio it's under Project Properties.

  6. #6
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Isn't C++ Suppose to be faster than .NET?

    Doesn't Windows give priority to the application with the focus? That's no kind of test at all. You need to run the separately with nothing else running and profile them.

  7. #7
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: Isn't C++ Suppose to be faster than .NET?

    Also, you are only testing terminal IO. Most programs where you
    are worried about speed performance do computing.

  8. #8
    Join Date
    May 2007
    Posts
    11

    Re: Isn't C++ Suppose to be faster than .NET?

    Replace endl with '\n'.

  9. #9
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Isn't C++ Suppose to be faster than .NET?

    Quote Originally Posted by Pale
    I have always heard that C++ was faster than C#.

    So I decided to do a test on which could count to 10000000 faster using a for loop.
    You are basing your tests on how fast the screen I/O is for each language. That is not a valid test.

    If you really were to test how fast a loop is:
    Code:
    StartYourTimer();
    
    for (int i = 0; i < 10000000; ++i )
    {
       // Do something that is not I/O related!
    }
    
    EndYourTimer();
    OutputTimerStats();
    Then you fill in those functions StartYourTimer(), EndYourTimer() and OutputTimerStats() with the appropriate functions that do just that. Adding I/O to the middle of timing tests automatically invalidates your test.

    Regards,

    Paul McKenzie

  10. #10
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: Isn't C++ Suppose to be faster than .NET?

    As I said, I think he's really testing Windows scheduling. Bring the C++ app to the front and I'd be willing to bet it would win.

  11. #11
    Join Date
    Sep 2002
    Location
    14° 39'19.65"N / 121° 1'44.34"E
    Posts
    9,815

    Re: Isn't C++ Suppose to be faster than .NET?

    Quote Originally Posted by Pale
    Isn't C++ Suppose to be faster than .NET?
    Who said that? I mean, what makes you think so? There are even scenarios where managed .NET code can execute faster than native code - for example, due to just-in-time compiling for the actual target CPU.

    However, and like others already said: More than the actual execution time of the code, what you are comparing here is likely to be the implementation of the runtime libraries used for I/O, the OS scheduler... And on top of that, I guess your C++ version is a probably debug build (which can be several orders of magnitude slower than a release build). It never makes sense to use debug builds for timing / profiling.

  12. #12
    Join Date
    Mar 2008
    Posts
    161

    Re: Isn't C++ Suppose to be faster than .NET?

    Quote Originally Posted by gstercken
    Who said that? I mean, what makes you think so? There are even scenarios where managed .NET code can execute faster than native code - for example, due to just-in-time compiling for the actual target CPU.

    However, and like others already said: More than the actual execution time of the code, what you are comparing here is likely to be the implementation of the runtime libraries used for I/O, the OS scheduler... And on top of that, I guess your C++ version is a probably debug build (which can be several orders of magnitude slower than a release build). It never makes sense to use debug builds for timing / profiling.
    No, its a "Release Child"

  13. #13
    Join Date
    Jun 2008
    Posts
    592

    Re: Isn't C++ Suppose to be faster than .NET?

    I don't have c# installed. Assuming you know c# well enough, I am sure you can translate this to c#?

    Code:
    #include <iostream>
    #include <windows.h>
    #include <math.h>
    
    using namespace std;
    
    int main()
    {
    	int I(0), J(0), K(0), T(0);
    	int Method(0);
    
    	SYSTEMTIME Time;
    
    	cout << "Please input the number of times to process: ";
    	cin >> J;
    	cout << endl;
    
    	cout << "Please select what method of process you want:" << endl;
    	cout << "0 to Process addition" << endl;
    	cout << "1 to Process randomization, division, multplication, power of and addition" << endl;
    	cout << endl;
    	cout << "Input: (0 or 1) ";
    	cin >> Method;
    	cout << endl;
    
    	T = GetTickCount();
    
    	for( I = 0; I <= J; I++ ){
    	  if( Method == 0 ){
    		if( K > 0xFFFFFF) K = 0;
    		K = K + 1;
    	  }else{
    		K = (rand() % 1) * 1000;
    		K = K * 2 / 3 * 5;
    		K = pow(K, 2);
    
    		GetLocalTime( &Time );
    		K = K + Time.wSecond;
    	  }
    	}
    
    	T = GetTickCount() - T;
    
    	cout << "The time to process is: " << T << "ms" << endl;
    	return 0;
    }
    I didn't code this. This was from vb6 vs vb.net. I only converted it to c++. I think this is a bit better to test the performance out. I am not saying that this test will prove c# or c++ is faster than each other, but this will give some insight on either or not c++ or c# is faster. A few people pointed out that a program language isn't all about speed. It is what the tool provides that you need to get the job done for you faster, more reliable, better readability and much more. I am not voting for c#, but just keep in mind on what one you really need. If you are looking for speed, I would think asm, c, c++ ...

    If you do port it to c#, make sure you use equivalent .net apis. I don't want to see p-invokes.

    Here is the code for the samething in vb6. I couldn't find the vb.net version

    Code:
    Option Explicit
    Private Declare Function GetTickCount Lib "kernel32" () As Long
    
    
    Dim I&, J&, K&, T&
    
    T = GetTickCount
    
    J = Val(Text1.Text)
    
    For I = 0 To J
      If Check1.Value = 0 Then
    	If K > &HFFFFFF Then K = 0
    	K = K + 1
      Else
    	K = Rnd(1) * 1000
    	K = K * 2 / 3 * 5
    	K = K ^ 2
    	K = K + Second(Now)
      End If
    Next
    
    T = GetTickCount - T
    Me.Caption = T
    Remember to tell your compiler to optimize your code. If you don't do that, what is the point in coding in c++ besides portability and its major role in games .

    If you don't know how to tell your compiler to optimize, I will tell you how to optimize your code in code::blocks. I think vc++ compiler actually makes better output for speed than gnu c++ compiler, but like I said, speed is only one factor.

    EDIT: the c++ uses a console while the vb6 version uses a window
    0100 0111 0110 1111 0110 0100 0010 0000 0110 1001 0111 0011 0010 0000 0110 0110 0110 1111 0111 0010
    0110 0101 0111 0110 0110 0101 0111 0010 0010 0001 0010 0001 0000 0000 0000 0000
    0000 0000 0000 0000

  14. #14
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Isn't C++ Suppose to be faster than .NET?

    It really boils down to where you want to spend your time. Consider a recent post asking how to retrieve the user that created a process. After much searching, I found the C++ code:

    Code:
    bool ExtractProcessOwner( HANDLE hProcess_i,   
                              CString& csOwner_o )   
    {   
       // Get process token   
       HANDLE hProcessToken = NULL;   
       if ( !::OpenProcessToken( hProcess_i, TOKEN_READ, &hProcessToken ) || !hProcessToken )   
       {   
          return false;   
       }   
      
       // First get size needed, TokenUser indicates we want user information from given token   
       DWORD dwProcessTokenInfoAllocSize = 0;   
       ::GetTokenInformation(hProcessToken, TokenUser, NULL, 0, &dwProcessTokenInfoAllocSize);   
      
       // Call should have failed due to zero-length buffer.   
       if( ::GetLastError() == ERROR_INSUFFICIENT_BUFFER )   
       {   
          // Allocate buffer for user information in the token.   
          PTOKEN_USER pUserToken = reinterpret_cast<ptoken_user>( new BYTE[dwProcessTokenInfoAllocSize] );   
          if (pUserToken != NULL)   
          {   
             // Now get user information in the allocated buffer   
             if (::GetTokenInformation( hProcessToken, TokenUser, pUserToken, dwProcessTokenInfoAllocSize, &dwProcessTokenInfoAllocSize ))   
             {   
                // Some vars that we may need   
                SID_NAME_USE   snuSIDNameUse;   
                TCHAR          szUser[MAX_PATH] = { 0 };   
                DWORD          dwUserNameLength = MAX_PATH;   
                TCHAR          szDomain[MAX_PATH] = { 0 };   
                DWORD          dwDomainNameLength = MAX_PATH;   
      
                // Retrieve user name and domain name based on user's SID.   
                if ( ::LookupAccountSid( NULL,   
                                         pUserToken->User.Sid,   
                                         szUser,   
                                         &dwUserNameLength,   
                                         szDomain,   
                                         &dwDomainNameLength,   
                                         &snuSIDNameUse ))   
                {   
                   // Prepare user name string   
                   csOwner_o = _T("\\\\");   
                   csOwner_o += szDomain;   
                   csOwner_o += _T("\\");   
                   csOwner_o += szUser;   
      
                   // We are done!   
                   CloseHandle( hProcessToken );   
                   delete [] pUserToken;   
      
                   // We succeeded   
                   return true;   
                }//End if   
             }// End if   
      
             delete [] pUserToken;   
          }// End if   
       }// End if   
      
       CloseHandle( hProcessToken );   
      
       // Oops trouble   
       return false;   
    }// End GetProcessOwner
    The equivalent in C# is less than 3 lines long. I suppose there is some satisfaction in writing your own, but for me, I'm more interested in getting the complete program finished instead of focusing on one small portion.

  15. #15
    Join Date
    Aug 1999
    Location
    <Classified>
    Posts
    6,882

    Re: Isn't C++ Suppose to be faster than .NET?

    Quote Originally Posted by GCDEF
    As I said, I think he's really testing Windows scheduling. Bring the C++ app to the front and I'd be willing to bet it would win.
    This must be the case.
    Regards,
    Ramkrishna Pawar

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured