Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Everyone says c++ is faster than c#, why?

Everyone says c++ is faster than c#, why?

Scheduled Pinned Locked Moved The Lounge
csharpc++algorithmsquestion
64 Posts 46 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P PIEBALDconsult

    C++ is filth. For real speed you need C. :cool:

    R Offline
    R Offline
    Rob Grainger
    wrote on last edited by
    #24

    That depends a lot on whether you want to reuse components such as sort algorithms. I doubt very much you can match std::sort performance with C code, except for hand-coding every damn sort. Even then, C++ optimisation is damn fine nowadays.

    "If you don't fail at least 90 percent of the time, you're not aiming high enough." Alan Kay.

    P 1 Reply Last reply
    0
    • R Rob Grainger

      That depends a lot on whether you want to reuse components such as sort algorithms. I doubt very much you can match std::sort performance with C code, except for hand-coding every damn sort. Even then, C++ optimisation is damn fine nowadays.

      "If you don't fail at least 90 percent of the time, you're not aiming high enough." Alan Kay.

      P Offline
      P Offline
      PIEBALDconsult
      wrote on last edited by
      #25

      Rob Grainger wrote:

      hand-coding every damn sort

      As appropriate for the specific task, yes.

      1 Reply Last reply
      0
      • A amagitech

        I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

        #include
        #include

        using namespace std;

        int main(){
        const clock_t beginTime = clock();
        for (int i = 2; i < 2000000; i++)
        {
        bool isPrime = true;
        for (int j = 2; j*j <= i; j++)
        {
        if (i%j == 0){
        isPrime = false;
        break;
        }
        }
        if (isPrime)
        cout << i << endl;
        }
        cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
        }

        c# is 9 seconds

        using System;

        namespace Console01
        {
        class Program
        {

            static void Main(string\[\] args)
            {
                DateTime beginTime = DateTime.Now;
                for (int i = 2; i <= 2000000; i++)
                {
                    bool isPrime = true;
                    for (int j = 2; j \* j < i; j++)
                    {
                        if (i % j == 0)
                        {
                            isPrime = false;
                            break;
                        }
                    }
                    if (isPrime)
                        Console.WriteLine(i);
                }
                TimeSpan ts = DateTime.Now - beginTime;
                Console.WriteLine(ts.Seconds);
            }
        
        }
        

        }

        G Offline
        G Offline
        Gjeltema
        wrote on last edited by
        #26

        This link is a blog series done by Raymond Chen and Rico Mariani where Raymond wrote a Chinese dictionary in C++ and Rico wrote a naïve line-by-line translation of the C++ code in C#. The C# code blew away the C++ code in performance. Raymond then did a number of ever more severe optimizations (including writing his own string class) to finally beat the naïve C# performance. Rico then optimized the C# code and again beat the C++ performance. Raymond then did a couple of more optimizations to finally beat the C#. The summary is thus: Doing a straightforward implementation in C# will yield really good performance (and is much quicker to implement, relative to C++), in many cases better than a straightforward implementation in C++. But, if you put in a significant amount of optimization effort, C++ CAN clearly outperform the C# code - as noted in the final blog post of that series, there's certain initial overhead (60ms in Rico's case) that the CLR imposes that you cannot optimize away in C#.

        P 1 Reply Last reply
        0
        • A amagitech

          I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

          #include
          #include

          using namespace std;

          int main(){
          const clock_t beginTime = clock();
          for (int i = 2; i < 2000000; i++)
          {
          bool isPrime = true;
          for (int j = 2; j*j <= i; j++)
          {
          if (i%j == 0){
          isPrime = false;
          break;
          }
          }
          if (isPrime)
          cout << i << endl;
          }
          cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
          }

          c# is 9 seconds

          using System;

          namespace Console01
          {
          class Program
          {

              static void Main(string\[\] args)
              {
                  DateTime beginTime = DateTime.Now;
                  for (int i = 2; i <= 2000000; i++)
                  {
                      bool isPrime = true;
                      for (int j = 2; j \* j < i; j++)
                      {
                          if (i % j == 0)
                          {
                              isPrime = false;
                              break;
                          }
                      }
                      if (isPrime)
                          Console.WriteLine(i);
                  }
                  TimeSpan ts = DateTime.Now - beginTime;
                  Console.WriteLine(ts.Seconds);
              }
          
          }
          

          }

          D Offline
          D Offline
          Dave Kreskowiak
          wrote on last edited by
          #27

          Rule #1 of bench-marking code like this is to make damn sure both pieces of code are on the same playing field. As you've already been told, they are not. NEVER EVER EVER put output code (WriteLine, cout, printf, setting a TextBox.Text property, ...) inside your timing code. If you need to print result strings, put the result values in a plain old, preallocated(!), array. Arrays works pretty much the same across all languages so there isn't much of an overhead difference between implementations. Output your data to the screen after you exit the timing code. This way, you're not timing the efficiency of the output code on top of your algorithm code. As you've seen, the differences between console, stream and even visual control implementations can be HUGE.

          A guide to posting questions on CodeProject

          Click this: Asking questions is a skill. Seriously, do it.
          Dave Kreskowiak

          J 1 Reply Last reply
          0
          • D Dave Kreskowiak

            Rule #1 of bench-marking code like this is to make damn sure both pieces of code are on the same playing field. As you've already been told, they are not. NEVER EVER EVER put output code (WriteLine, cout, printf, setting a TextBox.Text property, ...) inside your timing code. If you need to print result strings, put the result values in a plain old, preallocated(!), array. Arrays works pretty much the same across all languages so there isn't much of an overhead difference between implementations. Output your data to the screen after you exit the timing code. This way, you're not timing the efficiency of the output code on top of your algorithm code. As you've seen, the differences between console, stream and even visual control implementations can be HUGE.

            A guide to posting questions on CodeProject

            Click this: Asking questions is a skill. Seriously, do it.
            Dave Kreskowiak

            J Offline
            J Offline
            jeron1
            wrote on last edited by
            #28

            Dave Kreskowiak wrote:

            NEVER EVER EVER

            :laugh: Hmmm, sounds like you're waffling on this issue.

            "the debugger doesn't tell me anything because this code compiles just fine" - random QA comment "Facebook is where you tell lies to your friends. Twitter is where you tell the truth to strangers." - chriselst "I don't drink any more... then again, I don't drink any less." - Mike Mullikins uncle

            1 Reply Last reply
            0
            • Z ZurdoDev

              Personally, I see this more as a technical discussion than a programming question and therefore valid for the Lounge. :^) But I can see why you made the comment. Way more interesting than what is usually in the Lounge. :-\

              There are only 10 types of people in the world, those who understand binary and those who don't.

              J Offline
              J Offline
              Jeremy Falcon
              wrote on last edited by
              #29

              Agreed :thumbsup:

              Jeremy Falcon

              1 Reply Last reply
              0
              • P PIEBALDconsult

                C++ is filth. For real speed you need C. :cool:

                Sander RosselS Offline
                Sander RosselS Offline
                Sander Rossel
                wrote on last edited by
                #30

                C is filth. For real speed you need Assembler. :cool:

                Visit my blog at Sander's bits - Writing the code you need. Or read my articles at my CodeProject profile.

                Simplicity is prerequisite for reliability. — Edsger W. Dijkstra

                Regards, Sander

                1 Reply Last reply
                0
                • G Gjeltema

                  This link is a blog series done by Raymond Chen and Rico Mariani where Raymond wrote a Chinese dictionary in C++ and Rico wrote a naïve line-by-line translation of the C++ code in C#. The C# code blew away the C++ code in performance. Raymond then did a number of ever more severe optimizations (including writing his own string class) to finally beat the naïve C# performance. Rico then optimized the C# code and again beat the C++ performance. Raymond then did a couple of more optimizations to finally beat the C#. The summary is thus: Doing a straightforward implementation in C# will yield really good performance (and is much quicker to implement, relative to C++), in many cases better than a straightforward implementation in C++. But, if you put in a significant amount of optimization effort, C++ CAN clearly outperform the C# code - as noted in the final blog post of that series, there's certain initial overhead (60ms in Rico's case) that the CLR imposes that you cannot optimize away in C#.

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #31

                  Gjeltema wrote:

                  is much quicker to implement

                  Yes, and probably with lower maintenance requirements. As well as C# probably requiring a development team with an overall lower payroll. These are factors that really matter in real-world development. And if the result is "good enough", then call it done and move on.

                  1 Reply Last reply
                  0
                  • A amagitech

                    I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

                    #include
                    #include

                    using namespace std;

                    int main(){
                    const clock_t beginTime = clock();
                    for (int i = 2; i < 2000000; i++)
                    {
                    bool isPrime = true;
                    for (int j = 2; j*j <= i; j++)
                    {
                    if (i%j == 0){
                    isPrime = false;
                    break;
                    }
                    }
                    if (isPrime)
                    cout << i << endl;
                    }
                    cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
                    }

                    c# is 9 seconds

                    using System;

                    namespace Console01
                    {
                    class Program
                    {

                        static void Main(string\[\] args)
                        {
                            DateTime beginTime = DateTime.Now;
                            for (int i = 2; i <= 2000000; i++)
                            {
                                bool isPrime = true;
                                for (int j = 2; j \* j < i; j++)
                                {
                                    if (i % j == 0)
                                    {
                                        isPrime = false;
                                        break;
                                    }
                                }
                                if (isPrime)
                                    Console.WriteLine(i);
                            }
                            TimeSpan ts = DateTime.Now - beginTime;
                            Console.WriteLine(ts.Seconds);
                        }
                    
                    }
                    

                    }

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #32

                    What dreadful code. Try a proper Sieve of Eratosthenes in both languages. Sieve of Eratosthenes - Wikipedia, the free encyclopedia[^] And, as the others have said, don't judge by IO. Also, run each several times, discard the highest and lowest times, and take the average. And use optimized builds. P.S. Streams is a big reason I do not use C++. X|

                    1 Reply Last reply
                    0
                    • A amagitech

                      I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

                      #include
                      #include

                      using namespace std;

                      int main(){
                      const clock_t beginTime = clock();
                      for (int i = 2; i < 2000000; i++)
                      {
                      bool isPrime = true;
                      for (int j = 2; j*j <= i; j++)
                      {
                      if (i%j == 0){
                      isPrime = false;
                      break;
                      }
                      }
                      if (isPrime)
                      cout << i << endl;
                      }
                      cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
                      }

                      c# is 9 seconds

                      using System;

                      namespace Console01
                      {
                      class Program
                      {

                          static void Main(string\[\] args)
                          {
                              DateTime beginTime = DateTime.Now;
                              for (int i = 2; i <= 2000000; i++)
                              {
                                  bool isPrime = true;
                                  for (int j = 2; j \* j < i; j++)
                                  {
                                      if (i % j == 0)
                                      {
                                          isPrime = false;
                                          break;
                                      }
                                  }
                                  if (isPrime)
                                      Console.WriteLine(i);
                              }
                              TimeSpan ts = DateTime.Now - beginTime;
                              Console.WriteLine(ts.Seconds);
                          }
                      
                      }
                      

                      }

                      K Offline
                      K Offline
                      Kiriander
                      wrote on last edited by
                      #33

                      Don't trust all what you read. Too many people think of C# as the early Java (that was painfully slow) or don't get what a JIT is really about.

                      1 Reply Last reply
                      0
                      • A amagitech

                        I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

                        #include
                        #include

                        using namespace std;

                        int main(){
                        const clock_t beginTime = clock();
                        for (int i = 2; i < 2000000; i++)
                        {
                        bool isPrime = true;
                        for (int j = 2; j*j <= i; j++)
                        {
                        if (i%j == 0){
                        isPrime = false;
                        break;
                        }
                        }
                        if (isPrime)
                        cout << i << endl;
                        }
                        cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
                        }

                        c# is 9 seconds

                        using System;

                        namespace Console01
                        {
                        class Program
                        {

                            static void Main(string\[\] args)
                            {
                                DateTime beginTime = DateTime.Now;
                                for (int i = 2; i <= 2000000; i++)
                                {
                                    bool isPrime = true;
                                    for (int j = 2; j \* j < i; j++)
                                    {
                                        if (i % j == 0)
                                        {
                                            isPrime = false;
                                            break;
                                        }
                                    }
                                    if (isPrime)
                                        Console.WriteLine(i);
                                }
                                TimeSpan ts = DateTime.Now - beginTime;
                                Console.WriteLine(ts.Seconds);
                            }
                        
                        }
                        

                        }

                        K Offline
                        K Offline
                        KesavanandChavali
                        wrote on last edited by
                        #34

                        Remove cout and see... Somewhere I read streams in c++ aren't performant

                        1 Reply Last reply
                        0
                        • A Anthony Mushrow

                          After a quick check, what you're really comparing here is the efficiency of Console.WriteLine vs cout If you swap cout for printf you get much more similar times. In my case the C++ was a second faster than the C# but it's not a very fair comparison. Really I don't think you'll find much difference in performance of either.

                          S Offline
                          S Offline
                          Stefan_Lang
                          wrote on last edited by
                          #35

                          Exactly. To make a fair comparison, just eliminate all io within the loop. Or, better yet, don't do any io within the code block that is measured. That said, I wouldn't expect *any* meaningful difference for this code. it's just basic arithmetic that translates directly to assembly, and that goes for both C++ and C#.

                          GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                          1 Reply Last reply
                          0
                          • C Chris Maunder

                            We all know that VB is faster than them both.

                            cheers Chris Maunder

                            X Offline
                            X Offline
                            xiecsuk
                            wrote on last edited by
                            #36

                            Let's hear it for VB. Hip hip

                            1 Reply Last reply
                            0
                            • S Sascha Lefevre

                              I'm not an expert in this but I can tell you this much: - You didn't set a processor affinity. Stack swaps could have skewed your results. - You didn't set the process and thread priority to high. Your programs code have been interrupted by other threads. - Did you make sure you ran both programs with compiler optimization and without debugger/profiler attached? - Integer-arithmetic isn't representative for the overall speed of the language. Take a look here: Head-to-head benchmark: C++ vs .NET[^]

                              If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                              S Offline
                              S Offline
                              Stefan_Lang
                              wrote on last edited by
                              #37

                              That article provides a rather thorough comparison, but it focuses on library implementations, not the core language. Just from skimming over the results I spotted several remarks on 'lousy' implementations, and that alone is a dead giveaway that the results should be taken with a huge pint of salt.

                              GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                              1 Reply Last reply
                              0
                              • A amagitech

                                I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

                                #include
                                #include

                                using namespace std;

                                int main(){
                                const clock_t beginTime = clock();
                                for (int i = 2; i < 2000000; i++)
                                {
                                bool isPrime = true;
                                for (int j = 2; j*j <= i; j++)
                                {
                                if (i%j == 0){
                                isPrime = false;
                                break;
                                }
                                }
                                if (isPrime)
                                cout << i << endl;
                                }
                                cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
                                }

                                c# is 9 seconds

                                using System;

                                namespace Console01
                                {
                                class Program
                                {

                                    static void Main(string\[\] args)
                                    {
                                        DateTime beginTime = DateTime.Now;
                                        for (int i = 2; i <= 2000000; i++)
                                        {
                                            bool isPrime = true;
                                            for (int j = 2; j \* j < i; j++)
                                            {
                                                if (i % j == 0)
                                                {
                                                    isPrime = false;
                                                    break;
                                                }
                                            }
                                            if (isPrime)
                                                Console.WriteLine(i);
                                        }
                                        TimeSpan ts = DateTime.Now - beginTime;
                                        Console.WriteLine(ts.Seconds);
                                    }
                                
                                }
                                

                                }

                                I Offline
                                I Offline
                                irneb
                                wrote on last edited by
                                #38

                                As many others have also shown, your main issue is the cout streaming in C++ is less than optimal (to say the least). Also things like compiling to production settings (i.e. all optimizations possible) instead of debug, ensuring thread priority is set to high and cpu affinity set to ensure no other processes interfere and cause a cache reload during the test. All these thing could throw out any such benchmarking. But just to be nitpicky: You're using a simple clock to time your benchmark. In both C++ as well as C#, that has previously been seen to have lots of inaccuracies due to optimizations in the clock's implementation. To ensure the most accurate such timing (if you're not using a profiler instead - which BTW you should rather do) then rather use: - In C++ it depends on the system. Under Linux clock_gettime[^], under Windows QPC [^] is a better alternative - In C# you should be using Stopwatch[^] instead.

                                1 Reply Last reply
                                0
                                • A amagitech

                                  I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

                                  #include
                                  #include

                                  using namespace std;

                                  int main(){
                                  const clock_t beginTime = clock();
                                  for (int i = 2; i < 2000000; i++)
                                  {
                                  bool isPrime = true;
                                  for (int j = 2; j*j <= i; j++)
                                  {
                                  if (i%j == 0){
                                  isPrime = false;
                                  break;
                                  }
                                  }
                                  if (isPrime)
                                  cout << i << endl;
                                  }
                                  cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
                                  }

                                  c# is 9 seconds

                                  using System;

                                  namespace Console01
                                  {
                                  class Program
                                  {

                                      static void Main(string\[\] args)
                                      {
                                          DateTime beginTime = DateTime.Now;
                                          for (int i = 2; i <= 2000000; i++)
                                          {
                                              bool isPrime = true;
                                              for (int j = 2; j \* j < i; j++)
                                              {
                                                  if (i % j == 0)
                                                  {
                                                      isPrime = false;
                                                      break;
                                                  }
                                              }
                                              if (isPrime)
                                                  Console.WriteLine(i);
                                          }
                                          TimeSpan ts = DateTime.Now - beginTime;
                                          Console.WriteLine(ts.Seconds);
                                      }
                                  
                                  }
                                  

                                  }

                                  J Offline
                                  J Offline
                                  Jonas Hammarberg
                                  wrote on last edited by
                                  #39

                                  Comparing apples and pears ... **c** for (int i = 2; i **<** 2000000; i++) for (int j = 2; j*j **<=** i; j++) **c#** for (int i = 2; i **<=** 2000000; i++) for (int j = 2; j * j **<** i; j++) As it stands now, C does quite a few more loops than C# ... Change the loops (so that they are the same) and remove I/O from inside them. YMMV

                                  A 1 Reply Last reply
                                  0
                                  • J Jonas Hammarberg

                                    Comparing apples and pears ... **c** for (int i = 2; i **<** 2000000; i++) for (int j = 2; j*j **<=** i; j++) **c#** for (int i = 2; i **<=** 2000000; i++) for (int j = 2; j * j **<** i; j++) As it stands now, C does quite a few more loops than C# ... Change the loops (so that they are the same) and remove I/O from inside them. YMMV

                                    A Offline
                                    A Offline
                                    amagitech
                                    wrote on last edited by
                                    #40

                                    you righ'tit escaped me. I fixed now c# is 7 second.

                                    1 Reply Last reply
                                    0
                                    • A amagitech

                                      I used same algorithm for c# and c++. I have read c++ is faster than c# but my tests shows c# is faster than c++. What's wrong? My codes like this. c++ is 36 seconds

                                      #include
                                      #include

                                      using namespace std;

                                      int main(){
                                      const clock_t beginTime = clock();
                                      for (int i = 2; i < 2000000; i++)
                                      {
                                      bool isPrime = true;
                                      for (int j = 2; j*j <= i; j++)
                                      {
                                      if (i%j == 0){
                                      isPrime = false;
                                      break;
                                      }
                                      }
                                      if (isPrime)
                                      cout << i << endl;
                                      }
                                      cout << float(clock() - beginTime) / CLOCKS_PER_SEC;
                                      }

                                      c# is 9 seconds

                                      using System;

                                      namespace Console01
                                      {
                                      class Program
                                      {

                                          static void Main(string\[\] args)
                                          {
                                              DateTime beginTime = DateTime.Now;
                                              for (int i = 2; i <= 2000000; i++)
                                              {
                                                  bool isPrime = true;
                                                  for (int j = 2; j \* j < i; j++)
                                                  {
                                                      if (i % j == 0)
                                                      {
                                                          isPrime = false;
                                                          break;
                                                      }
                                                  }
                                                  if (isPrime)
                                                      Console.WriteLine(i);
                                              }
                                              TimeSpan ts = DateTime.Now - beginTime;
                                              Console.WriteLine(ts.Seconds);
                                          }
                                      
                                      }
                                      

                                      }

                                      T Offline
                                      T Offline
                                      Thornik
                                      wrote on last edited by
                                      #41

                                      Any benchmark test never ever should include I/O! You're not experienced here, so we forgive you. :)

                                      A 1 Reply Last reply
                                      0
                                      • T Thornik

                                        Any benchmark test never ever should include I/O! You're not experienced here, so we forgive you. :)

                                        A Offline
                                        A Offline
                                        amagitech
                                        wrote on last edited by
                                        #42

                                        :) I am junior developer. I need to learn more software culture. But I don't have any teacher(who is senior developer) for learning this subjects. So I take risk to asking dummy questions :)

                                        1 Reply Last reply
                                        0
                                        • S Sascha Lefevre

                                          Good catch!

                                          If the brain were so simple we could understand it, we would be so simple we couldn't. — Lyall Watson

                                          S Offline
                                          S Offline
                                          SortaCore
                                          wrote on last edited by
                                          #43

                                          Also, you're using < in one for loop, and <= in the other.

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups