2013-09-28 34 views
3

與Java的實現相比,下面的DART代碼非常慢。與java的實現相比,爲什麼這個Dart代碼很慢?

//test.dart 
import 'dart:io'; 
void main(){ 
for(int i = 0; i < 1 << 25;i++){ 
    stdout.write(i); // or directly print(i); 
} 
    stdout.close(); 
} 

Java版本:

//Test.java 
import java.io.*; 
public class Test{ 
public static void main(String[]args)throws Exception { 
    try{ 
     PrintWriter out = new PrintWriter(System.out); 
     for(int i = 0;i < 1 << 25; i++){ 
      out.print(i); 
     } 
     out.close(); 
    }catch(Exception e){} 
    } 
} 

$時間Java測試>的/ dev/null的

real 0m6.421s 
user 0m0.046s 
sys  0m0.031s 

$時間鏢Test.dart>的/ dev/null的

real 0m51.978s 
user 0m0.015s 
sys  0m0.078s 

默認情況下,Dart中的stdout/print()是無緩衝的嗎?有沒有像java的PrintWriter?謝謝。 (更新:熱身VM後,標準輸出比Java慢2倍)

real 0m15.497s 
user 0m0.046s 
sys 0m0.047s 

========================== ================================================== ===

更新2013年9月30日

我已經實現自定義的緩衝區兩個鏢和java代碼作進一步比較,現在的結果如下:

//test.dart 
final int SIZE = 8192; 
final int NUM = 1 << 25; 
void main(){ 
    List<int> content = new List(SIZE); 
    content.fillRange(0, SIZE, 0); 
    for(int i = 0; i < NUM;i++){ 
    if(i % SIZE == 0 && i > 0) 
     print(content); 
    content[i % SIZE] = i; 
    } 
    if (NUM % SIZE ==0) 
    print(content); 
    else 
    print(content.sublist(0, NUM % SIZE)); 
} 

Java版本:

//Test.java 
import java.util.Arrays; 
public class Test{ 
public static final int SIZE = 8192; 
public static final int NUM = 1 << 25; 
public static void main(String[]args)throws Exception { 
    try{ 
     int[] buf = new int[SIZE]; 
     for(int i = 0;i < NUM; i++){ 
      if(i % SIZE == 0 && i > 0) 
       System.out.print(Arrays.toString(buf)); 
      buf[i % SIZE] = i;    
     } 
     if(NUM % SIZE == 0) 
      System.out.print(Arrays.toString(buf)); 
     else 
     { 
      int[] newbuf = new int[NUM % SIZE]; 
      newbuf = Arrays.copyOfRange(buf, 0, (NUM % SIZE)); 
      System.out.print(Arrays.toString(newbuf)); 
     } 
     }catch(Exception e){} 
    } 
} 

$時間Java測試>的/ dev/null的

real 0m7.397s 
user 0m0.031s 
sys  0m0.031s 

$時間鏢test.dart>的/ dev/null的

real 0m22.406s 
user 0m0.015s 
sys  0m0.062s 

正如你看到的,飛鏢依然比java慢3倍。

+0

的【答案】(http://stackoverflow.com/questions/16788467/console-print-speed)到類似的問題似乎變得有點更快的速度:2X慢3倍,慢。也許它可能會幫助你進一步優化。 –

+0

@PixelElephant:謝謝你的回覆。我已經閱讀了答案,並試圖直接將輸出寫入文件,而不是在控制檯上打印,但它仍然比java慢3倍。也許內部飛鏢虛擬機或其他需要更好的優化。 –

回答

1

也許你的代碼沒有被虛擬機優化。 只有「頻繁」使用的函數纔會被編譯並作爲本機代碼執行。 通常對於這樣的基準測試,您必須將測試代碼放入函數並執行熱身。對於爲例:

//test.dart 
import 'dart:io'; 
void f(nb_shift) { 
for(int i = 0; i < 1 << nb_shift;i++){ 
    stdout.write(i); // or directly print(i); 
} 
} 

void main(){ 
    //warm up: 
    f(3); 
    // the test 
    f(25); 
    stdout.close(); 
} 

薩科

+0

感謝您的回覆,真的很有幫助。熱身後,現在stdout比java慢2倍。 –

相關問題