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. General Programming
  3. C / C++ / MFC
  4. Java vs. C++

Java vs. C++

Scheduled Pinned Locked Moved C / C++ / MFC
c++javavisual-studioquestion
22 Posts 8 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.
  • L Offline
    L Offline
    LCI
    wrote on last edited by
    #1

    Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

    D R M N E 6 Replies Last reply
    0
    • L LCI

      Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #2

      LCI wrote:

      This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs.

      There are way too many variables involved in order for this to be an accurate assessment. You are, in effect, comparing apples to oranges.


      "A good athlete is the result of a good and worthy opponent." - David Crow

      "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

      L 1 Reply Last reply
      0
      • D David Crow

        LCI wrote:

        This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs.

        There are way too many variables involved in order for this to be an accurate assessment. You are, in effect, comparing apples to oranges.


        "A good athlete is the result of a good and worthy opponent." - David Crow

        "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

        L Offline
        L Offline
        LCI
        wrote on last edited by
        #3

        Not sure i understand why this is not an fair assessment. Can you elaborate when you say that i am comparing apples to oranges?

        D B 2 Replies Last reply
        0
        • L LCI

          Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

          R Offline
          R Offline
          Russell
          wrote on last edited by
          #4

          please, try this:

          int j;
          double k;

          for (int i = 0; i < 1000000000; i++)
          {

          int j = 5;

          j++;

          j *= 2;

          j /= 2;

          j--;

          double k = 5.0;

          k++;

          k *= 2;

          k /= 2;

          k--;

          }

          how many seconds?:-D


          Russell

          M J 2 Replies Last reply
          0
          • L LCI

            Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

            M Offline
            M Offline
            Mike Dimmick
            wrote on last edited by
            #5

            It very much depends on the actual problem, and on the optimization settings you select, for C++. I would expect that a decent optimizer could detect that the operations within the loop cancel each other out and it might even conclude that the loop itself doesn't do anything, leaving you with no code whatever. Indeed, when run with the optimization options /Oxs, that is exactly what Visual Studio 2005 does. So in fact does Visual C++ 6.0. I was trying to make it do more work, so asked it to print the final values of j and k. It simply passed the literals 5 and 5.0 into printf. I used the /FAs switch to generate an assembly listing with source code. This can be daunting if you're not familiar with x86 assembly, but it's pretty obvious that the compiler didn't generate any instructions for the loop. (It even did crazy tricks like loading the address of GetTickCount, which I used for time measurement, into a register!) On my computer a debug build, with optimizations disabled, took 23 seconds to execute. The 'optimizations disabled' version is incredibly naive, as close to a literal translation as possible, and actually performs the operations as coded, although it performs some straightforward conversions (e.g. multiplying and dividing integers by 2 by bit-shifting, and using floating-point addition to multiply k by 2). It also stores results back into main memory rather than just leaving them in a register, for example. Almost all Java implementations now use a JIT (Just-In-Time) compiler. This is able to perform some of the optimizations that a C++ compiler can do and so can eliminate some of the unnecessary operations (like avoiding write-back to memory for local variables), but not all. If you want to do a real test, you'll have to actually make the operations somehow dependent on the value of the loop variable, so the compilers don't just throw the code away, and allow the C++ compiler to optimize the code.

            Stability. What an interesting concept. -- Chris Maunder

            1 Reply Last reply
            0
            • R Russell

              please, try this:

              int j;
              double k;

              for (int i = 0; i < 1000000000; i++)
              {

              int j = 5;

              j++;

              j *= 2;

              j /= 2;

              j--;

              double k = 5.0;

              k++;

              k *= 2;

              k /= 2;

              k--;

              }

              how many seconds?:-D


              Russell

              M Offline
              M Offline
              Mike Dimmick
              wrote on last edited by
              #6

              0, if you build an optimized version of the C++ code (see my full answer below, but basically the C++ compiler works out that the body of the loop is a no-op and throws the whole loop away!)

              Stability. What an interesting concept. -- Chris Maunder

              R L 2 Replies Last reply
              0
              • L LCI

                Not sure i understand why this is not an fair assessment. Can you elaborate when you say that i am comparing apples to oranges?

                D Offline
                D Offline
                David Crow
                wrote on last edited by
                #7

                LCI wrote:

                Can you elaborate when you say that i am comparing apples to oranges?

                Why do people insist on comparing C++ and Java? Consider reading The Design and Evolution of C++ (D&E) to see why C++ is the way it is, and consider both languages in the light of their design criteria. Those criteria will obviously differ from the criteria of Sun's Java team. Despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++.


                "A good athlete is the result of a good and worthy opponent." - David Crow

                "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

                1 Reply Last reply
                0
                • M Mike Dimmick

                  0, if you build an optimized version of the C++ code (see my full answer below, but basically the C++ compiler works out that the body of the loop is a no-op and throws the whole loop away!)

                  Stability. What an interesting concept. -- Chris Maunder

                  R Offline
                  R Offline
                  Russell
                  wrote on last edited by
                  #8

                  I was only trying to do the easyest optimization to beat 2.5 sec. ;);P


                  Russell

                  1 Reply Last reply
                  0
                  • L LCI

                    Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

                    N Offline
                    N Offline
                    Nemanja Trifunovic
                    wrote on last edited by
                    #9

                    And where is the C++ code? I see only Java in your post. Also, which compiler are you using and what optimizations?


                    Programming Blog utf8-cpp

                    1 Reply Last reply
                    0
                    • R Russell

                      please, try this:

                      int j;
                      double k;

                      for (int i = 0; i < 1000000000; i++)
                      {

                      int j = 5;

                      j++;

                      j *= 2;

                      j /= 2;

                      j--;

                      double k = 5.0;

                      k++;

                      k *= 2;

                      k /= 2;

                      k--;

                      }

                      how many seconds?:-D


                      Russell

                      J Offline
                      J Offline
                      jhwurmbach
                      wrote on last edited by
                      #10

                      In fact, the optimizer should have taken care of this. It should, in fact, have made the int into a register. What went wrong?


                      Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                      George Orwell, "Keep the Aspidistra Flying", Opening words

                      R E 2 Replies Last reply
                      0
                      • L LCI

                        Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

                        E Offline
                        E Offline
                        El Corazon
                        wrote on last edited by
                        #11

                        You can write bad code in C++ and you can write bad code in Java. When you try to compare them you can deliberately show the advantages of either one over the other, but only for that example. It can give you a false sense of what each language is capable of. It is "a little knowledge is a dangerous thing" type problem. Seriously, if you are going to try to compare apples and oranges, understand what the strengths and weaknesses are. A good compiler can save you from some of your errors, but only so far. how about 0.75 seconds for C++. If I turn on full analysis, as mentioned above, I get 0 seconds. Intel can figure out the loop never uses the variable entries and removes it as useless code. A print of the values of k and j at the end will keep the code. Oh... I forgot, that is on my slowest computer.... ;) That is the point of understanding how the language and compiler/framework work together. If you only know the "syntax" of any language, you only know half of what you are doing.

                        _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

                        1 Reply Last reply
                        0
                        • J jhwurmbach

                          In fact, the optimizer should have taken care of this. It should, in fact, have made the int into a register. What went wrong?


                          Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                          George Orwell, "Keep the Aspidistra Flying", Opening words

                          R Offline
                          R Offline
                          Russell
                          wrote on last edited by
                          #12

                          yes, but optimization is something that is not everytime clear/sure for the user...look at your words:

                          jhwurmbach wrote:

                          he optimizer should have taken care of this

                          the only way to know what appens after compile is to look to the assembler code...or, better, don't think to compare the same code written in different languages without considering optimizations, code-shortcuts, assembler translation, ... Optimization is a too wide chapter to think to understand everithing with only a sample code:(


                          Russell

                          J 1 Reply Last reply
                          0
                          • R Russell

                            yes, but optimization is something that is not everytime clear/sure for the user...look at your words:

                            jhwurmbach wrote:

                            he optimizer should have taken care of this

                            the only way to know what appens after compile is to look to the assembler code...or, better, don't think to compare the same code written in different languages without considering optimizations, code-shortcuts, assembler translation, ... Optimization is a too wide chapter to think to understand everithing with only a sample code:(


                            Russell

                            J Offline
                            J Offline
                            jhwurmbach
                            wrote on last edited by
                            #13

                            Russell` wrote:

                            optimization is something that is not everytime clear/sure for the user

                            Sure. Mike Dimmik did his study while I was writing my reply. I got 19,3 and 3,4*10^-7 seconds in debug and relase, respectivly. I took this as "quite a lot" and "practically nothing" and asked where the 2,5 seconds came from. I doubt that there is a computer 10 times as fast as my double Xeon 2.4 Ghz...


                            Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                            George Orwell, "Keep the Aspidistra Flying", Opening words

                            R 1 Reply Last reply
                            0
                            • J jhwurmbach

                              Russell` wrote:

                              optimization is something that is not everytime clear/sure for the user

                              Sure. Mike Dimmik did his study while I was writing my reply. I got 19,3 and 3,4*10^-7 seconds in debug and relase, respectivly. I took this as "quite a lot" and "practically nothing" and asked where the 2,5 seconds came from. I doubt that there is a computer 10 times as fast as my double Xeon 2.4 Ghz...


                              Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                              George Orwell, "Keep the Aspidistra Flying", Opening words

                              R Offline
                              R Offline
                              Russell
                              wrote on last edited by
                              #14

                              2.5 seconds comes from Java, he took 11 secs in C++ ... I think that he was using the DEBUG mode. ...but ....you know...they are only unuseful numbers X| ;)


                              Russell

                              1 Reply Last reply
                              0
                              • L LCI

                                Anyone have any idea if Java is faster than C++ at run time? This code was executed and it took java 2.5 secs to complete whereas it took c++ 11 secs. Any input is appreciated. thanks, long start_time = System.currentTimeMillis(); System.out.println("Starting... "); for (int i = 0; i < 1000000000; i++) { int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; } System.out.println("Ending. Time taken: " + (System.currentTimeMillis() - start_time) + " milisec");

                                B Offline
                                B Offline
                                bob16972
                                wrote on last edited by
                                #15

                                Thats because java has an internal piece of code that gets inserted secretly that resembles this... for (int i = 0; i < 1000000000; i++) // *************************** // Java specific internal code if ((bInVeryBigLoop==true) && (bCodeServesNoObviousPurpose==true)) { // User must be running a benchmark against c++ break; } // End java specific internal code // ******************************* int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; }

                                J 1 Reply Last reply
                                0
                                • L LCI

                                  Not sure i understand why this is not an fair assessment. Can you elaborate when you say that i am comparing apples to oranges?

                                  B Offline
                                  B Offline
                                  bob16972
                                  wrote on last edited by
                                  #16

                                  For one, how can you verify that the loops were fully processed without some output of the value in the end? You need to modify a value on each iteration, and use the final value in some output in both systems to prevent optimizations in Java from throwing the whole loop away and not even processing it. You may be the victim of a false positive since it may not have processed things as you think in both environments. You need to understand what happens in optimized and debug modes to properly set up your benchmarks and to fully appreciate and digest the results of your tests. You can inadvertantly benchmark using debug mode so make sure, if you haven't already, to only benchmark in releasemode.

                                  1 Reply Last reply
                                  0
                                  • J jhwurmbach

                                    In fact, the optimizer should have taken care of this. It should, in fact, have made the int into a register. What went wrong?


                                    Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                                    George Orwell, "Keep the Aspidistra Flying", Opening words

                                    E Offline
                                    E Offline
                                    El Corazon
                                    wrote on last edited by
                                    #17

                                    jhwurmbach wrote:

                                    What went wrong?

                                    answer:

                                    jhwurmbach wrote:

                                    should have

                                    /\ || right there. Don't assume the compiler fixes everything. Compile time is the absolute worst time to try to figure out what a programmer "wants" to achieve and then attempt to get there. Some compilers do a better job than others, so it depends on which compiler you are using. Is that a Fuji apple or a Granny Smith? :) I am not saying every programmer has to learn what the compiler does with their code. But if you are actually concerned with, or absolutely need performance, then you MUST know what the compiler will do with your code. Hand tuning an algorithm might take half an hour and save you 75% of your execution time. A large error could save you considerably more. A compiler can only do so much with junk code before it also outputs junk. Compilers aren't mind readers and none that I know of have heuristic analysis to try to figure out what your intent was. Until they make a mind reading compiler, we're all in the same boat. A compiler actually listens to what we tell it, even when we want it to obey what we mean, not what we type.

                                    _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

                                    J 1 Reply Last reply
                                    0
                                    • E El Corazon

                                      jhwurmbach wrote:

                                      What went wrong?

                                      answer:

                                      jhwurmbach wrote:

                                      should have

                                      /\ || right there. Don't assume the compiler fixes everything. Compile time is the absolute worst time to try to figure out what a programmer "wants" to achieve and then attempt to get there. Some compilers do a better job than others, so it depends on which compiler you are using. Is that a Fuji apple or a Granny Smith? :) I am not saying every programmer has to learn what the compiler does with their code. But if you are actually concerned with, or absolutely need performance, then you MUST know what the compiler will do with your code. Hand tuning an algorithm might take half an hour and save you 75% of your execution time. A large error could save you considerably more. A compiler can only do so much with junk code before it also outputs junk. Compilers aren't mind readers and none that I know of have heuristic analysis to try to figure out what your intent was. Until they make a mind reading compiler, we're all in the same boat. A compiler actually listens to what we tell it, even when we want it to obey what we mean, not what we type.

                                      _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

                                      J Offline
                                      J Offline
                                      jhwurmbach
                                      wrote on last edited by
                                      #18

                                      We were concerned with the speed of execution, and when the compilers optimisation did not kick in (as it should), I asked "Why?" On the whole, I agree. This is part of why the original posting was so sensless: What good is a fast nonsense-loop, when all Java-applications have a sluggish GUI anyway? :rolleyes::cool: When the application has a bottleneck you determine it and fix it. Probably with a design change or a different algorithm. But you certainly are not paied for doing the compilers work. It has to, and will, optimize code in a way I can not possibly do by hand.


                                      Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                                      George Orwell, "Keep the Aspidistra Flying", Opening words

                                      E 1 Reply Last reply
                                      0
                                      • B bob16972

                                        Thats because java has an internal piece of code that gets inserted secretly that resembles this... for (int i = 0; i < 1000000000; i++) // *************************** // Java specific internal code if ((bInVeryBigLoop==true) && (bCodeServesNoObviousPurpose==true)) { // User must be running a benchmark against c++ break; } // End java specific internal code // ******************************* int j = 5; j++; j *= 2; j /= 2; j--; double k = 5.0; k++; k *= 2; k /= 2; k--; }

                                        J Offline
                                        J Offline
                                        jhwurmbach
                                        wrote on last edited by
                                        #19

                                        This comes scaringly close to reality... :laugh:


                                        Though I speak with the tongues of men and of angels, and have not money, I am become as a sounding brass, or a tinkling cymbal.
                                        George Orwell, "Keep the Aspidistra Flying", Opening words

                                        1 Reply Last reply
                                        0
                                        • M Mike Dimmick

                                          0, if you build an optimized version of the C++ code (see my full answer below, but basically the C++ compiler works out that the body of the loop is a no-op and throws the whole loop away!)

                                          Stability. What an interesting concept. -- Chris Maunder

                                          L Offline
                                          L Offline
                                          LCI
                                          wrote on last edited by
                                          #20

                                          Do you know if Java has the concept of Debug vs. release builds?

                                          M 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