Thread: Java is 1000 times faster than c++ on my computer???

  1. #1
    Registered User
    Join Date
    Jun 2009
    Location
    Seattle
    Posts
    6

    Java is 1000 times faster than c++ on my computer???

    Ok, this is driving me batty. I recently had an assignment to implement Floyds algorithm and Dijkstras on a graph with 5403 vertices. (in java) my program was running impossibly slow so I started troubleshooting. As part of that troubleshooting I wrote a 3 level nested for loop in Java, and the same set of loops in C++. The Java version is running 1000 times faster than the C++ version. I just KNOW Java is not 1000 times faster than C++ Can anybody suggest what might be going on here? Here's the code
    Code:
    In C++:
    
    #include <iostream>
    #include <ctime>
    using namespace std;
    
    int main(int argc, char *argv[])
    {
    	unsigned start = time(0);
    	cout << "start is " << start << endl;
    	int count=0;
        for (int i=0;i<5404;i++)
        {
        	cout << "i = " << i << endl;
        	for (int j=0;j<5404;j++)
        	{
            	for (int k=0;k<5404;k++)
            	{
            		count ++;
            	}
            }
    	}
    	unsigned finish = time(0);
    	unsigned total = finish-start;
    	cout << "n^3 took: "<< total << "seconds" <<  endl;
        return 0;
    }// end main
    
    Output: 
    	.
    	.
    	.
    i = 5400
    
    i = 5401
    
    i = 5402
    
    i = 5403
    
    finish is 1243916727
    
    n^3 took: 323seconds
    
    
    Java:
    public class Main 
    {
    	public static void main(String[] args)
    	{
    		int count=0;
    		long start = System.currentTimeMillis();
    		for(int k=0;k<5404;k++)
    		{
    			System.out.println( "k= " + k);
    			for (int i=0;i<5404;i++)
    			{
    				for(int j=0;j<5404;j++)
    				{
    					count++;
    				}
    			}
    		}
    		long finish=System.currentTimeMillis();
    		long totalTime=(finish-start);
    		System.out.println("n^3 took " + totalTime / 1000.0 + " seconds");
    		
    	}	
    } // end main
    
    Output:
    	.
    	.
    	.
    k= 5400
    
    k= 5401
    
    k= 5402
    
    k= 5403
    
    n^3 took 0.332 seconds
    Just to flesh out the details. My computer is an amd dual core 2.7Ghz with 4Gb Ram running Ubuntu 9.10.

    Java is
    java version "1.6.0_0"
    OpenJDK Runtime Environment (IcedTea6 1.4.1) (6b14-1.4.1-0ubuntu7)
    OpenJDK 64-Bit Server VM (build 14.0-b08, mixed mode)

    C compiler is:
    g++ (Ubuntu 4.3.3-5ubuntu4) 4.3.3
    Copyright (C) 2008 Free Software Foundation, Inc.

    commands
    java Main
    g++ main.cpp
    Last edited by darin722; 06-01-2009 at 10:45 PM.

  2. #2
    Master Apprentice phantomotap's Avatar
    Join Date
    Jan 2008
    Posts
    5,108
    It's pretty simple really... Java simply isn't doing anything.

    Add something to the innermost loop to prevent JIT from eliminating the inner loops or compile with the heaviest optimization your C++ compiler allows before trying to compile them. (That would be "-O3" for GCC.)

    Soma

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    If you enable even the tiniest bit of optimisation on the C++ code, then it too will see that the j and k looks achieve absolutely nothing as well, and remove them from the code.

    count is never used, so anything which "calculates" count can easily be removed from the code.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Actually, I'm quite surprised it's ONLY 1000 times slower - considering that if the Java code is probably optimized so that it doesn't do 5404 * 5404 => 29 million inner loop iterations [which indeed doesn't do much].

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    matsp: Well, there's the I/O overhead.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  6. #6
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by CornedBee View Post
    matsp: Well, there's the I/O overhead.
    True!

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  7. #7
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Quote Originally Posted by darin722 View Post
    I just KNOW Java is not 1000 times faster than C++
    Languages are neither fast nor slow. Individual programs written with a particular implementation with particular data sets run with varying execution speeds. All we know from this test is that a particular Java program is 1000 times faster than a particular C++ program.

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    Or rather, this particular Java program compiled by this particular compiler running on this particular VM with these particular options

    is 1000 times faster than

    this particular C++ program compiled by this particular compiler with these particular options.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    Registered User
    Join Date
    Apr 2008
    Posts
    890
    Correct. None of which will stop Sun from marketing how "fast" Java is :-)

  10. #10
    Registered User
    Join Date
    Jun 2009
    Location
    Seattle
    Posts
    6
    Hm, so basically, Java is optimizing the program into just a single for loop (the outter one)?

    With the -O3 flag turned on, the C version appeared slightly faster than previously, but still nowhere near as fast as the java version. (I didn't let it run to completion)

    If java is ignoring the inner loops because they are essentially not used, printing count as the program terminates should prevent this, yes?

    --and Thanks for all the replies. I did indeed understand that Java was not 1000 times faster than C++ in all cases, I just didn't expect it to be THAT much faster in any case.

  11. #11
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    I wouldn't count on printing count at the end of program absolutely means that the loops actually get executed. I have seen compilers figure out that "the result of this is X" when it comes to simple loops that just adds 1 each time.

    I'm very surprised that -O3 doesn't lead to good results, it normally does a good job on optimizing away loops.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  12. #12
    The larch
    Join Date
    May 2006
    Posts
    3,573
    MingW doesn't optimize the loops away either.

    However

    (in java) my program was running impossibly slow so I started troubleshooting.
    The program that is slow is actually doing something (can't optimize inner loops away), as the unoptimized C++ program is doing something. It's not going to get faster than that.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  13. #13
    int x = *((int *) NULL); Cactus_Hugger's Avatar
    Join Date
    Jul 2003
    Location
    Banks of the River Styx
    Posts
    902
    What I get:
    Code:
    $ g++ -o cpp.test test.cpp -O3
    $ gcj -o java.test Main.java --main=Main
    $ javac Main.java
    $ ./cpp.test
    ...
    i = 5402
    i = 5403
    n^3 took: 0.0599821seconds
    $ java Main
    k= 498
    k= 499
    n^3 took 43.118 seconds
    (5404 would take too long - extrapolated, it would've been: 466.02 seconds/7m46s)
    $ ./java.test
    k= 497
    k= 498
    k= 499
    n^3 took 79.429 seconds
    (5404 would take too long - extrapolated, it would've been: 858.47 seconds/14m18s)
    $ gcj -o java.test Main.java --main=Main -O3
    k= 5401
    k= 5402
    k= 5403
    n^3 took 0.117 seconds
    So, the winner is C++, but by only a factor of 2. My software & hardware:
    Code:
    gcc version 4.3.2
    
    java version "1.6.0_13"
    Java(TM) SE Runtime Environment (build 1.6.0_13-b03)
    Java HotSpot(TM) 64-Bit Server VM (build 11.3-b02, mixed mode)
    
    model name	: Intel(R) Core(TM)2 Duo CPU     T7300  @ 2.00GHz
    cache size	: 4096 KB
    cpu cores	: 2
    (I tweaked the timing code in the C++ version to use gettimeofday, for the subsecond timings.)
    Last edited by Cactus_Hugger; 06-02-2009 at 04:49 PM.
    long time; /* know C? */
    Unprecedented performance: Nothing ever ran this slow before.
    Any sufficiently advanced bug is indistinguishable from a feature.
    Real Programmers confuse Halloween and Christmas, because dec 25 == oct 31.
    The best way to accelerate an IBM is at 9.8 m/s/s.
    recursion (re - cur' - zhun) n. 1. (see recursion)

  14. #14
    Registered User
    Join Date
    Jun 2009
    Location
    Seattle
    Posts
    6
    Quote Originally Posted by anon View Post
    MingW doesn't optimize the loops away either.

    However



    The program that is slow is actually doing something (can't optimize inner loops away), as the unoptimized C++ program is doing something. It's not going to get faster than that.
    Anon,
    By impossibly slow I mean that the n^3 loop was going to take 4.5 hours to complete. That's what set me off on doing time tests. It appears that Eclipse was the problem. When running the java program from eclipse, each iteration of the outter for loop takes roughly 3 seconds. In the real program all it is doing is array[row][col] = math.min[array[row][col],array[otherRow][otherCol])
    By running the program from a terminal window the time went from 4.5 hours to 4.5 minutes. Still, I would never have though that any java program would be faster, let alone so much faster, than compiled c++.

  15. #15
    Registered User
    Join Date
    Jun 2009
    Location
    Seattle
    Posts
    6
    Cactus_Hugger. Now you've got me even more curious. It doesn't look like our computers are all that different in specs on the surface. Mine's an AMD 7750 with 512K cache and variable processor speed 1.3-2.7, 4G ram, and dual cores, but our times on the java program are so different. Are you executing it from the command line or from within an IDE?


    And Matsp: Huh, thanks for the thought. I've never given any thought to what a compiler could or might do to optimize my code. It's interesting that that's never come up in my CS program so far.
    Last edited by darin722; 06-02-2009 at 10:49 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Tabbed Windows with MDI?
    By willc0de4food in forum Windows Programming
    Replies: 25
    Last Post: 05-19-2005, 10:58 PM
  2. Computer will not boot.
    By RealityFusion in forum Tech Board
    Replies: 25
    Last Post: 09-10-2004, 04:05 PM
  3. Regarding Undergraduate Computer Majors
    By UnregdRegd in forum A Brief History of Cprogramming.com
    Replies: 11
    Last Post: 10-04-2003, 11:55 AM
  4. This is my last night on this computer.
    By joshdick in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 07-12-2003, 01:33 AM
  5. Which distro should I run on my old computer?
    By joshdick in forum Tech Board
    Replies: 5
    Last Post: 04-09-2003, 01:37 AM