Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Code speed problem

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Location
    Europe, Lithuania
    Posts
    10
    My Mood
    Where
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Code speed problem

    Hi, i've came across an exercise to find what number from 1 to 10000 has maximum number of divisors.
    Here's my solution:

    public class Main {
     
    	// main method that is executed when program starts
    	public static void main(String[] args) {
    		Main m = new Main();
    	}
     
    	// declare pieces array
    	private PieceOfNumber[] pieces = new PieceOfNumber[2];
     
    	public Main(){
    		// for loop to start pieces
    		for(int i = 0; i < 2; i++){
    			pieces[i] = new PieceOfNumber((i * 5000) + 1, (i * 5000) + 5000);
    			pieces[i].start();
    		}
    	}
     
    	// create int array which stores number divisors
    	private int[] nums = new int[10000];
     
    	// onDone method is called when PieceOfNumber finishes its work
    	// and piece that have finished is passed in
    	private void onDone(PieceOfNumber p){
    		int from = p.getFrom() - 1;
    		int to = p.getTo();
     
    		for(int i = from; i < to; i++){
    			// add values to final numbers array
    			nums[i] = p.getArray()[i - from];
    		}
    	}
     
    	// method to ckeck if all pieces is done
    	private void onAllDone(){
    		boolean allDone = true;
     
    		for(PieceOfNumber piece: pieces){
    			if(!piece.isDone())
    				allDone = false;
    		}
     
    		// if all done, find an answer
    		if(allDone)
    			findMax();
    	}
     
    	private void findMax(){
    		int max = 0;
    		int num_with_max = -1;
     
    		for(int i = 0; i < 10000; i++){
    			// check if array value is greater than current max
    			if(nums[i] > max){
    				max = nums[i];
    				num_with_max = i;
    			}
    		}
     
    		// print out answer
    		System.out.printf("\n%d has %d divisors.", num_with_max, max);
    	}
     
    	public class PieceOfNumber extends Thread {
     
    		private int from;
    		private int to;
     
    		private boolean done = false;
     
    		// array to store values of numbers from to
    		private int numbers[] = new int[5000];
    		// current array index
    		private int index = 0;
     
    		public PieceOfNumber(int from, int to){
    			super();
     
    			// set values for looping
    			this.from = from;
    			this.to = to;
    		}
     
    		// some getters to return needed information
    		public int[] getArray(){
    			return numbers;
    		}
     
    		public int getFrom(){
    			return from;
    		}
     
    		public int getTo(){
    			return to;
    		}
     
    		public boolean isDone(){
    			return done;
    		}
     
    		@Override
    		public void run(){
    			// try to loop through numbers
     
    			try{
    				loop();
    			}catch(Exception e){
    				e.printStackTrace();
    			}
    		}
     
    		// loop method
    		public void loop() throws Exception {
    			// print from what number to what number looping
    			System.out.printf("Looping from %d to %d.\n", from - 1, to);
     
    			for(int pos = from; pos < to; pos++){
    				for(int num = 0; num < 10000; num++){
    					// check if number is greater than 0, because it can cause arithmetical error
    					if(num > 0){
    						// check if number is divisible by n and add it to array
    						if(divisible(pos, num)){
    							numbers[index]++;
    						}
    					}
    				}
     
    				index++;
    			}
     
    			// call onDone
    			done = true;
    			onDone(this);
    			onAllDone();
     
    			// stop current thread
    			try{
    				join();
    			}catch(InterruptedException e){
    				e.printStackTrace();
    			}
    		}
     
    		// boolean to check if number is divisible by n
    		protected boolean divisible(int num, int n){
    			if(num % n == 0)
    				return true;
    			else
    				return false;
    		}
    	}
    }

    This code works, but the problem is that it works slower than this:

    for(int x = 1; x < 10000; x++){
        for(int y = 1; y < 10000; y++){
            // code here
        }
    }

    So I wanna know why. Thanks for good and not so good answers.
    Last edited by Gasis; August 12th, 2014 at 05:06 PM.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Code speed problem

    Can you whittle the code down to the two equivalent parts? And how much slower? Have you timed it or used a profiler to analyze why there are differences?

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Code speed problem

    How many actions are taken in your code?

    How many actions are taken in the second piece of code?

    If you can't figure it out by going through your code by hand, you might want to create a static timer and increment it every time you do anything, then print it out at the end of the program. I bet it's a pretty high number.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. #4
    Junior Member
    Join Date
    Jun 2014
    Location
    Europe, Lithuania
    Posts
    10
    My Mood
    Where
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Code speed problem

    OK, I understand that i'm doing many actions in my code, but shouldn't two threads do it faster?

    P.S. The number is 7559 with 64 divisors.
    Last edited by Gasis; August 12th, 2014 at 01:44 PM.

  5. #5
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: Code speed problem

    Quote Originally Posted by Gasis View Post
    OK, I understand that i'm doing many actions in my code, but shouldn't two threads do it faster?
    Depends on many factors. The size of the problem, the machine you are running it on, the number of other processes running on the same machine, etc.
    Multithreading can sometimes slow things down instead of speeding it up. This happens because creating, starting, and synchronizing threads is expensive. Only for large problems (where "large" depends on the system specs) multithreading becomes feasible.

  6. #6
    Junior Member
    Join Date
    Jun 2014
    Location
    Europe, Lithuania
    Posts
    10
    My Mood
    Where
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Code speed problem

    I've tested this code in Android os. If not multi-threading, what else could speed it up? Multi-threading is useful only for difficult operations like internet connection and so on, right?

  7. #7
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Code speed problem

    Not a single comment in your code. How is anyone supposed to know what you're doing?

    How does the program end? When do the threads stop?

    If this code terminated correctly, I can't believe it would even run for 4 seconds, so I doubt the timed results you've reported are accurate. I supposed there are processors still so slow that would allow it, but only if the computer name is Commodore. Are you running on a multi-core processor? If so, then 4 seconds is definitely unreasonable, and I believe you're seeing those results because some other OS or programming environment process is terminating threads that aren't doing anything, ending the program for you.

    Review your code, add some comments, terminate the program when the solution has been found, and come back with your updated code, revelations, or new questions

  8. #8
    Junior Member
    Join Date
    Jun 2014
    Location
    Europe, Lithuania
    Posts
    10
    My Mood
    Where
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Code speed problem

    I tested this on single-core, not on pc. I will update code.

  9. #9
    Member Ada Lovelace's Avatar
    Join Date
    May 2014
    Location
    South England UK
    Posts
    414
    My Mood
    Angelic
    Thanks
    27
    Thanked 61 Times in 55 Posts

    Default Re: Code speed problem

    I do not see why execution speed is such an issue really, but if you
    want blazing speed write the same thing in assembly or C

    Language choice nowadays only has a very small baring on the speed that
    a application runs. Java is not "slow" anymore - as was thought of in the past.
    Yes, the byte-code translation and then the compiling phase takes a bit longer
    than standard compilation time but it's still very quick and much better since
    the newer Java versions were released (after 3.0 I believe).

    Unless you are writing code to target a specific application (video games, operating systems)
    then speed is never really going to cause an issue overall.

    Just my two cents on it.

    Wishes Ada xx
    If to Err is human - then programmers are most human of us all.
    "The Analytical Engine offers a new, a vast, and a powerful language . . .
    for the purposes of mankind
    ."
    Augusta Ada Byron, Lady Lovelace (1851)

  10. #10
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Code speed problem

    Quote Originally Posted by Gasis View Post
    I tested this on single-core, not on pc. I will update code.
    Why would using multiple threads make your application "faster" on a single core?

    --- Update ---

    Quote Originally Posted by Ada Lovelace View Post
    Unless you are writing code to target a specific application (video games, operating systems)
    then speed is never really going to cause an issue overall.
    You might mean this as an oversimplificiation, but it's not really true. Speed (or more specifically, responsiveness) is hugely important in almost every non-trivial application.

    As for your comment about assembly or C, recommended reading: Java performance - Wikipedia, the free encyclopedia

    However, I do agree that OP seems worried about the wrong things. After all, premature optimization is the root of all evil.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  11. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Ada Lovelace (August 13th, 2014)

Similar Threads

  1. Code will not work to change speed with the up and down arrow keys
    By rtucker1023 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: April 4th, 2013, 04:09 PM
  2. Object Speed problem! (move();)
    By Optimizer in forum What's Wrong With My Code?
    Replies: 9
    Last Post: January 13th, 2013, 06:24 PM
  3. Need...more...speed!
    By nPeep in forum Java Networking
    Replies: 8
    Last Post: September 6th, 2010, 11:07 AM
  4. KB/s download speed calculating
    By Koâk in forum Java Theory & Questions
    Replies: 2
    Last Post: December 16th, 2009, 03:05 PM