2017-09-05 8 views
-3

私は奇数と偶数の2つの異なるデータベースに1000個の乱数を入力するためのプログラムをJavaで作成しました。コードは正常に実行されていますが、実行には約1分かかります。実行時間を最小限に抑えるにはどうすればよいですか?ここで どのようにJavaプログラムの実行時間を最小限に抑えるには?

はコードです:代わりたび 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

から forループの後に一度だけそれを行います。これは、addBatch(挿入/更新の集約とそれらを一度にすべて実行すること)の全体的なポイントです。

以下のコメントでBorisが述べたように、rewriteBatchedStatementsもオンにすると、Borisは実行を高速化します。達成方法については、hereを参照してください。

+2

'rewriteBatchedStatements'を有効にすると便利でしょうか? –

+0

@BoristheSpider良い点、ありがとう! – alfasin

関連する問題