Impl faster ADD

This commit is contained in:
nicksavers 2014-06-03 23:35:29 +02:00
parent e5e65b48d3
commit de0f67ae3b
2 changed files with 87 additions and 1 deletions

View File

@ -97,7 +97,7 @@ public class DataWord {
// todo: add can be done in more efficient way
// todo without BigInteger quick hack
public void add(DataWord word){
public void add2(DataWord word){
BigInteger result = value().add( word.value() );
byte[] bytes = result.toByteArray();
@ -106,6 +106,20 @@ public class DataWord {
System.arraycopy(bytes, 0, data.array(), 32 - bytes.length, bytes.length);
this.data = data.array();
}
// By : Holger
// From : http://stackoverflow.com/a/24023466/459349
public void add(DataWord word) {
if (this.data.length != 32 || word.data.length != 32)
throw new IllegalArgumentException();
byte[] result = new byte[32];
for (int i = 31, overflow = 0; i >= 0; i--) {
int v = (this.data[i] & 0xff) + (word.data[i] & 0xff) + overflow;
result[i] = (byte) v;
overflow = v >>> 8;
}
this.data = result;
}
// todo: mull can be done in more efficient way
// todo: with shift left shift right trick

View File

@ -0,0 +1,72 @@
package org.ethereum.vm;
import static org.junit.Assert.*;
import java.math.BigInteger;
import org.junit.Test;
public class DataWordTest {
@Test
public void testAddPerformance() {
boolean enabled = true;
if(enabled) {
byte[] one = new byte[] { 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54,
0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01,
0x31, 0x54, 0x41, 0x01, 0x31, 0x54, 0x41, 0x01, 0x31, 0x54,
0x41, 0x01, 0x31, 0x54, 0x41 }; // Random value
int ITERATIONS = 10000000;
long now1 = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
DataWord x = new DataWord(one);
x.add(x);
}
System.out.println("Add1: " + (System.currentTimeMillis() - now1) + "ms");
long now2 = System.currentTimeMillis();
for (int i = 0; i < ITERATIONS; i++) {
DataWord x = new DataWord(one);
x.add2(x);
}
System.out.println("Add2: " + (System.currentTimeMillis() - now2) + "ms");
} else {
System.out.println("ADD performance test is disabled.");
}
}
@Test
public void testAdd2() {
byte[] two = new byte[32];
two[31] = 0x01; // 0x00000000000000000000000000000000000000000000000000000000000001
DataWord x = new DataWord(two);
x.add(new DataWord(two));
System.out.println(new BigInteger(1, x.data));
DataWord y = new DataWord(two);
y.add2(new DataWord(two));
System.out.println(new BigInteger(1, y.data));
}
@Test
public void testAdd3() {
byte[] three = new byte[32];
for (int i = 0; i < three.length; i++) {
three[i] = (byte) 0xff;
}
DataWord x = new DataWord(three);
x.add(new DataWord(three));
assertEquals(32, x.data.length);
System.out.println(new BigInteger(1, x.data));
// FAIL
// DataWord y = new DataWord(three);
// y.add2(new DataWord(three));
// System.out.println(new BigInteger(1, y.data));
}
}