Why is this Dart code so slow compared to java's implementation? - dart

The dart codes as follows is extremely slow compared to java's implementation.
//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 version:
//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){}
}
}
$ time java Test > /dev/null
real 0m6.421s
user 0m0.046s
sys 0m0.031s
$ time dart Test.dart > /dev/null
real 0m51.978s
user 0m0.015s
sys 0m0.078s
Is stdout/print() unbuffered by default in Dart? Is there something like java's PrintWriter? thanks. (Update: after warming up vm, stdout is 2x slower than java )
real 0m15.497s
user 0m0.046s
sys 0m0.047s
===============================================================================
Update Sep 30, 2013
I have implemented custom buffers for both dart and java codes to make a further comparing,now the result is as follows:
//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 version:
//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){}
}
}
$ time java Test > /dev/null
real 0m7.397s
user 0m0.031s
sys 0m0.031s
$ time dart test.dart > /dev/null
real 0m22.406s
user 0m0.015s
sys 0m0.062s
As you see, dart is still 3x slower than java.

Maybe your code does not get optimized by the VM.
Only "frequenly" used functions are compiled and executed as native code.
Usually for such benchmark, you have to put the tested code into a function and perform a warmup. For exemple:
//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();
}
Nicolas

Related

My do while loop is not entering the while loop

I'm trying to complete my homework assignment and am having trouble. The instructions state that I need to change the while expression to a not but whenever I do it wont enter the loop.
import java.util.Scanner;
public class GuessNumberApp {
public static void main(String[] args) {
final int LIMIT = 10;
System.out.println("Guess the number!");
System.out.println("I'm thinking of a number from 1 to " + LIMIT);
System.out.println();
// get a random number between 1 and the limit
double d = Math.random() * LIMIT; // d is >= 0.0 and < limit
int number = (int) d; // convert double to int
number++; // int is >= 1 and <= limit
Scanner sc = new Scanner(System.in);
int count = 1;
int guess;
do {
System.out.print("Your guess: ");
guess = Integer.parseInt(sc.nextLine());
}
while (guess != number); {
if (guess < 1 || guess > LIMIT) {
System.out.println("Invalid guess. Try again.");
}
else if (guess < number) {
System.out.println("Too low.");
count++;
}
else if (guess > number) {
System.out.println("Too high.");
count++;
}
}
System.out.println("You guessed it in " + count + " tries.\n");
System.out.println("Bye!");
}
}

Difference between print and stdout.printf in flushing

When I run a sample in Vala-ThreadSamples:
Original version:
int question(){
for (var i = 0; i < 3; i++){
print (".");
Thread.usleep (800000);
stdout.flush ();
}
return 42;
}
void main(){
question();
}
Modified version:
int question(){
for (var i = 0; i < 3; i++){
print(".");
Thread.usleep (800000);
}
return 42;
}
void main(){
question();
}
Two version gets the same output:
print a dot and wait, which repeat three times.
Why print will flush every times?

Dart _psapi not found

I am trying to call WinAPI. I have copy-past code from docs:
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';
main() {
int EnumProcesses(
Pointer<Uint32> lpidProcess, int cb, Pointer<Uint32> lpcbNeeded) {
final _EnumProcesses = _psapi.lookupFunction<
Int32 Function(
Pointer<Uint32> lpidProcess, Uint32 cb, Pointer<Uint32> lpcbNeeded),
int Function(Pointer<Uint32> lpidProcess, int cb,
Pointer<Uint32> lpcbNeeded)>('EnumProcesses');
return _EnumProcesses(lpidProcess, cb, lpcbNeeded);
}
}
If you've got a reference to win32, you don't need to copy this code also -- you should already have the EnumProcesses API available to you.
Here's a simple example of how to use it:
import 'dart:ffi';
import 'dart:io';
import 'package:ffi/ffi.dart';
import 'package:win32/win32.dart';
int printModules(int processID) {
// Print the process identifier.
print('\nProcess ID: $processID');
// Get a handle to the process.
final hProcess = OpenProcess(
PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processID);
if (hProcess == 0) {
return 1;
}
// Get a list of all the modules in this process.
final hMods = allocate<IntPtr>(count: 1024);
final cbNeeded = allocate<Uint32>();
if (EnumProcessModules(
hProcess, hMods, sizeOf<IntPtr>() * 1024, cbNeeded.cast()) ==
1) {
for (var i = 0; i < ((cbNeeded.value / sizeOf<IntPtr>()).floor()); i++) {
final szModName = allocate<Uint16>(count: MAX_PATH).cast<Utf16>();
// Get the full path to the module's file.
final hModule = hMods.elementAt(i).value;
final moduleValue =
'0x${hModule.toRadixString(16).padLeft(sizeOf<IntPtr>(), '0').toUpperCase()}';
if (GetModuleFileNameEx(hProcess, hModule, szModName, MAX_PATH) != 0) {
// Print the module name and handle value.
print('\t${szModName.unpackString(MAX_PATH)} ($moduleValue)');
}
free(szModName);
}
}
free(hMods);
free(cbNeeded);
// Release the handle to the process.
CloseHandle(hProcess);
return 0;
}
void main() {
final aProcesses = allocate<Uint32>(count: 1024);
final cbNeeded = allocate<Uint32>();
// Get the list of process identifiers.
if (EnumProcesses(aProcesses, sizeOf<Uint32>() * 1024, cbNeeded.cast()) ==
0) {
print('EnumProcesses failed.');
exit(1);
}
// Calculate how many process identifiers were returned.
final cProcesses = (cbNeeded.value / sizeOf<Uint32>()).floor();
// Print the names of the modules for each process.
for (var i = 0; i < cProcesses; i++) {
printModules(aProcesses[i]);
}
}

C# CRC-16-CCITT 0x8408 Polynomial. Help needed

I am new in communications programming. Basically, I need to get the hex equivalent of the CRC output. I have a hex string which is the parameter -
EE0000000015202020202020202020202020323134373030353935
This is concatenation of two strings. The output I need is E6EB in hex or 59115 in ushort. I tried different approaches based on what I found in the web but to no avail. The polynomial that I should be using is 0x8408, which is [CRC-16-CCITT][1], http://en.wikipedia.org/wiki/Polynomial_representations_of_cyclic_redundancy_checks.
I tried this approach, CRC_CCITT Kermit 16 in C#, but the output is incorrect. I also tried the bitwise ~ operator as some suggested for reverse computation, but still failed.
Any help is very much appreciated.
RevEng reports:
% ./reveng -s -w 16 EE0000000015202020202020202020202020323134373030353935e6eb
width=16 poly=0x1021 init=0xffff refin=true refout=true xorout=0xffff check=0x906e name="X-25"
So there's your CRC. Note that the CRC is reflected, where 0x8408 is 0x1021 reflected.
I found a solution and I'll post them in case someone will encounter the same.
private ushort CCITT_CRC16(string strInput)
{
ushort data;
ushort crc = 0xFFFF;
byte[] bytes = GetBytesFromHexString(strInput);
for (int j = 0; j < bytes.Length; j++)
{
crc = (ushort)(crc ^ bytes[j]);
for (int i = 0; i < 8; i++)
{
if ((crc & 0x0001) == 1)
crc = (ushort)((crc >> 1) ^ 0x8408);
else
crc >>= 1;
}
}
crc = (ushort)~crc;
data = crc;
crc = (ushort)((crc << 8) ^ (data >> 8 & 0xFF));
return crc;
}
private byte[] GetBytesFromHexString(string strInput)
{
Byte[] bytArOutput = new Byte[] { };
if (!string.IsNullOrEmpty(strInput) && strInput.Length % 2 == 0)
{
SoapHexBinary hexBinary = null;
try
{
hexBinary = SoapHexBinary.Parse(strInput);
if (hexBinary != null)
{
bytArOutput = hexBinary.Value;
}
}
catch (Exception ex)
{
throw ex;
}
}
return bytArOutput;
}
import System.Runtime.Remoting.Metadata.W3cXsd2001 for SoapHexBinary.

lua_pcall cause "cannot resume dead coroutine"

i have such c++ code below to call lua code
for (int i =0; i < 2000; i++)
{
lua_getglobal(g_L, "AnalyzeScript");
lua_pushstring(g_L, "1");
lua_pushstring(g_L, "2");
lua_pushstring(g_L, "3");
if(lua_pcall(g_L,3,0,0) != 0)
{
// char temp[200]={0}; sprintf(temp, "err: %s", lua_tostring(g_L, -1));
// MessageBoxA(0,temp,0,0);
}
lua code like below
local cnt = 0
function AnalyzeScript(foldername, filename, pOut)
cnt = cnt + 1
print(cnt)
end
every thing is ok, except "cannot resume dead coroutine"(which coroutine is in another place)
it looks like that 2000 times to call lua func ruin the lua stack, if i change 2000 to 200, every goes ok!
why?
I could not reproduce your error. I've changed the code a little:
/* test.c */
#include "lua.h"
#include "lauxlib.h"
void main() {
int i;
lua_State *g_L = luaL_newstate();
luaL_openlibs(g_L);
luaL_dofile(g_L, "s.lua");
for (i =0; i < 2000; i++)
{
lua_getglobal(g_L, "AnalyzeScript");
lua_pushstring(g_L, "1");
lua_pushstring(g_L, "2");
lua_pushstring(g_L, "3");
if(lua_pcall(g_L,3,0,0) != 0)
{
// char temp[200]={0}; sprintf(temp, "err: %s", lua_tostring(g_L, -1));
// MessageBoxA(0,temp,0,0);
}
}
lua_close (g_L);
}
It was compiled in my Linux with the following command (I have Lua distribution installed in /fakepath/lua-5.2.0):
gcc test.c -I/fakepath/lua-5.2.0/src /fakepath/lua-5.2.0/src/liblua.a -lm -ldl
File test.lua is exactly what you've posted.
Maybe the problem is somewhere else...

Resources