2017-09-05 12 views
-3

나는 두 개의 서로 다른 데이터베이스에 홀수와 짝수로 1000 개의 난수를 입력하는 프로그램을 자바로 만들었다. 코드가 잘 실행되고 있지만 실행하는 데 거의 1 분이 걸립니다. 실행 시간을 최소화하려면 어떻게합니까? 여기 자바 프로그램의 실행 시간을 최소화하는 방법은 무엇입니까?

은 코드 대신마다 setIntps.executeUpdate(); (및 ps3.executeUpdate();)를 호출의

import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.PreparedStatement; 
import java.sql.SQLException; 
import java.text.DecimalFormat; 
import java.text.NumberFormat; 
import java.util.Random; 

public class Test1 extends Thread { 

public static void main(String[] args) throws ClassNotFoundException, SQLException { 
    long start = System.currentTimeMillis(); 

    int evencount = 0; 
    int oddcount = 0; 
    int breakcon = 0; 
    int breakcon1 = 0; 

    Class.forName("com.mysql.jdbc.Driver"); 
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1" + "?useSSL=false", "root", 
      "1234"); 
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db2" + "?useSSL=false", "root", 
      "1234"); 

    try { 

     Class.forName("com.mysql.jdbc.Driver"); 

     for (int n = 1; n <= 1000; n++) { 
      Random r = new Random(); 
      int val = r.nextInt(100000); 

      if (val % 2 == 0) { 
       PreparedStatement ps = con.prepareStatement(" insert into try values (?)"); 
       ps.setInt(1, val); 
       ps.executeUpdate(); 
       ps.addBatch(); 
       breakcon = breakcon + 1; 
       if (breakcon % 500 == 0 || breakcon == val) 
        ps.executeBatch(); 
       evencount++; 

      } else { 
       try { 

        Class.forName("com.mysql.jdbc.Driver"); 
        PreparedStatement ps3 = conn.prepareStatement(" insert into try1 values (?)"); 
        ps3.setInt(1, val); 
        ps3.executeUpdate(); 
        ps3.addBatch(); 
        breakcon1 = breakcon1 + 1; 
        if (breakcon1 % 500 == 0 || breakcon1 == val) 
         ps3.executeBatch(); 

        oddcount++; 

       } 

       catch (Exception e2) { 
        System.out.println(e2); 
       } 
      } 
     } 

    } 

    catch (Exception e) { 
     System.out.println(e); 
    } 

    long end = System.currentTimeMillis(); 
    NumberFormat formatter = new DecimalFormat("#0.00000"); 
    System.out.println("Execution time is " + formatter.format((end - start)/1000d) + " seconds"); 
    System.out.println(oddcount + evencount); 

} 
} 
+0

SQL 일괄 처리를 살펴 보겠습니다. –

+0

@JoeC 어떻게해야합니까? 설명해주십시오. – sujitha

+1

이러한 종류의 질문은 [codereview.SE]에 더 나은 질문입니다. 실행 코드 개선에 관한 내용이기 때문에 – Jens

답변

2

-에 대한 루프 후 한 번만 해. 이것이 addBatch (집계 삽입/업데이트를 한 번에 모두 실행하는 것)의 요점입니다.

Boris가 아래 주석에서 언급했듯이 rewriteBatchedStatements도 켜면 Boris가 실행 속도를 훨씬 빠르게 할 수 있습니다. 달성 방법은 here을 참조하십시오.

+2

'rewriteBatchedStatements'를 켜는 것이 도움이 될 것 같습니까? –

+0

@BoristheSpider 좋은 지적, 감사합니다! – alfasin