diff --git a/ProjectHome.md b/ProjectHome.md new file mode 100644 index 0000000..8fdf87f --- /dev/null +++ b/ProjectHome.md @@ -0,0 +1,9 @@ +Short Java examples which too large to place in a blog, but not a complete library. + +--- + +YourKit is kindly supporting open source projects with its full-featured Java Profiler. +YourKit, LLC is the creator of innovative and intelligent tools for profiling +Java and .NET applications. Take a look at YourKit's leading software products: +[YourKit Java Profiler](http://www.yourkit.com/java/profiler/index.jsp) and +[.NET Profiler](http://www.yourkit.com/.net/profiler/index.jsp">YourKit). \ No newline at end of file diff --git a/pom.xml b/pom.xml deleted file mode 100644 index db126dd..0000000 --- a/pom.xml +++ /dev/null @@ -1,42 +0,0 @@ - - - 4.0.0 - - com.google.code.java.core - examples - 1.0 - - - - junit - junit - 4.8.2 - - - - net.sf.trove4j - trove4j - 2.0.2 - - - - org.javolution - javolution - 5.2.6 - - - - joda-time - joda-time - 1.6.2 - - - - org.jmock - jmock - 2.5.1 - - - \ No newline at end of file diff --git a/src/main/java/com/google/code/java/core/bytebuffer/AsciiText.java b/src/main/java/com/google/code/java/core/bytebuffer/AsciiText.java deleted file mode 100644 index bfb3b51..0000000 --- a/src/main/java/com/google/code/java/core/bytebuffer/AsciiText.java +++ /dev/null @@ -1,94 +0,0 @@ -package com.google.code.java.core.bytebuffer; - -import java.nio.ByteBuffer; - -/** - * @author peter.lawrey - */ -public class AsciiText implements CharSequence { - private final byte[] values = new byte[128]; - private byte length = 0; - - public AsciiText() { - } - - public int length() { - return length; - } - - public char charAt(int index) { - if (index >= length) throw new IndexOutOfBoundsException(); - return (char) (values[index] & 0xFF); - } - - public CharSequence subSequence(int start, int end) { - return toString().subSequence(start, end); - } - - @Override - public String toString() { - return length < 0 ? null : new String(values, 0, length); - } - - public void copyFrom(CharSequence s) { - if (s instanceof AsciiText) { - copyFrom((AsciiText) s); - return; - } - if (s == null) { - length = -1; - return; - } - if (s.length() > values.length) throw new IllegalStateException("String too long."); - length = (byte) s.length(); - for (int i = 0; i < length; i++) - values[i] = (byte) s.charAt(i); - } - - public void copyFrom(AsciiText s) { - length = s.length; - if (length > 0) - System.arraycopy(s.values, 0, values, 0, length); - } - - public void readFrom(ByteBuffer bb) { - length = bb.get(); - if (length > 0) - bb.get(values, 0, length); - } - - public void writeTo(ByteBuffer bb) { - bb.put(length); - if (length > 0) - bb.put(values, 0, length); - } - - @Override - public int hashCode() { - int hash = 0; - for (int i = 0; i < length; i++) - hash = 31 * hash + (values[i] & 0xFF); - return hash; - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof AsciiText)) return false; - if (obj == this) return true; - AsciiText other = (AsciiText) obj; - if (length != other.length) return false; - for (int i = 0; i < length; i++) - if (values[i] != other.values[i]) return false; - return true; - } - - public void clear() { - length = -1; - } - - public static AsciiText of(CharSequence s) { - AsciiText text = new AsciiText(); - text.copyFrom(s); - return text; - } -} diff --git a/src/main/java/com/google/code/java/core/bytebuffer/ByteBufferSpecificSerializer.java b/src/main/java/com/google/code/java/core/bytebuffer/ByteBufferSpecificSerializer.java deleted file mode 100644 index 4ef6312..0000000 --- a/src/main/java/com/google/code/java/core/bytebuffer/ByteBufferSpecificSerializer.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.google.code.java.core.bytebuffer; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -/** - * @author peter.lawrey - */ -public class ByteBufferSpecificSerializer /*implements ObjectSerializer*/ { - public static final AsciiText MPG4 = AsciiText.of("video/mpg4"); - public static final AsciiText KEYNOTE_TITLE = AsciiText.of("Javaone Keynote"); - public static final AsciiText KEYNOTE_URI = AsciiText.of("http://javaone.com/keynote.mpg"); - public static final AsciiText BILL_GATES = AsciiText.of("Bill Gates"); - public static final AsciiText STEVE_JOBS = AsciiText.of("Steve Jobs"); - public static final AsciiText KEYNOTE_LARGE = AsciiText.of("http://javaone.com/keynote_large.jpg"); - public static final AsciiText KEYNOTE_SMALL = AsciiText.of("http://javaone.com/keynote_thumbnail.jpg"); - final MediaContent created = new MediaContent(); - final MediaContent deserialized = new MediaContent(); - - final ByteBuffer bb = ByteBuffer.allocateDirect(4 * 1024).order(ByteOrder.nativeOrder()); - byte[] cachedBytes = {}; - - public MediaContent deserialize(byte[] array) throws Exception { - bb.clear(); - bb.put(array); - bb.flip(); - - deserialized.clear(); - deserialized.readFrom(bb); - return deserialized; - } - - public byte[] serialize(MediaContent content) throws Exception { - bb.clear(); - content.writeTo(bb); - bb.flip(); - // if you use NIO, a byte[] isn't required. - byte[] bytes = bb.remaining() == cachedBytes.length ? cachedBytes : (cachedBytes = new byte[bb.remaining()]); - bb.get(bytes); - return bytes; - } - - public String getName() { - return "ByteBuffer-specific"; - } - - public MediaContent create() throws Exception { - created.clear(); - Media media = created.getMedia(); - media.setCopyright(null); - media.setFormat(MPG4); - media.setPlayer(Media.Player.JAVA); - media.setTitle(KEYNOTE_TITLE); - media.setUri(KEYNOTE_URI); - media.setDuration(1234567); - media.setSize(123); - media.setHeight(0); - media.setWidth(0); - media.setBitrate(0); - media.addToPerson(BILL_GATES); - media.addToPerson(STEVE_JOBS); - MediaContent content = new MediaContent(media); - Image image0 = content.acquireImage(0); - image0.setHeight(0); - image0.setTitle(KEYNOTE_TITLE); - image0.setUri(KEYNOTE_LARGE); - image0.setWidth(0); - image0.setSize(Image.Size.LARGE); - Image image1 = content.acquireImage(1); - image1.setHeight(0); - image1.setTitle(KEYNOTE_TITLE); - image1.setUri(KEYNOTE_SMALL); - image1.setWidth(0); - image1.setSize(Image.Size.SMALL); - return content; - } -} diff --git a/src/main/java/com/google/code/java/core/bytebuffer/ByteBuffers.java b/src/main/java/com/google/code/java/core/bytebuffer/ByteBuffers.java deleted file mode 100644 index c35ae9d..0000000 --- a/src/main/java/com/google/code/java/core/bytebuffer/ByteBuffers.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.google.code.java.core.bytebuffer; - -import java.nio.ByteBuffer; - -/** - * @author peter.lawrey - */ -public enum ByteBuffers { - ; - - public static void read(ByteBuffer bb, AsciiText text) { - text.readFrom(bb); - } - - public static int readInt(ByteBuffer bb) { - int n = bb.get(); - if (n == -128) - return bb.getInt(); - return n; - } - - public static long readLong(ByteBuffer bb) { - int n = bb.get(); - if (n == -128) - return bb.getLong(); - return n; - } - - public static void write(ByteBuffer bb, Enum anEnum) { - bb.put((byte) anEnum.ordinal()); - } - - public static int readOrdinal(ByteBuffer bb) { - return bb.get() & 0xFF; - } - - public static void write(ByteBuffer bb, int num) { - if (num < -127 || num > 127) { - bb.put((byte) -128); - bb.putInt(num); - } else { - bb.put((byte) num); - } - } - - public static void write(ByteBuffer bb, long num) { - if (num < -127 || num > 127) { - bb.put((byte) -128); - bb.putLong(num); - } else { - bb.put((byte) num); - } - } - - public static void write(ByteBuffer bb, AsciiText text) { - text.writeTo(bb); - } -} diff --git a/src/main/java/com/google/code/java/core/bytebuffer/Image.java b/src/main/java/com/google/code/java/core/bytebuffer/Image.java deleted file mode 100644 index b3061a8..0000000 --- a/src/main/java/com/google/code/java/core/bytebuffer/Image.java +++ /dev/null @@ -1,148 +0,0 @@ -package com.google.code.java.core.bytebuffer; - -import java.nio.ByteBuffer; - -import static com.google.code.java.core.bytebuffer.ByteBuffers.*; - -public class Image { - public enum Size { - SMALL, LARGE - } - - private static final Size[] SIZES = Size.values(); - - private final AsciiText _uri = new AsciiText(); - private final AsciiText _title = new AsciiText(); - private int _width; - private int _height; - private Size _size; - - public Image() { - } - - - public Image(int height, String title, String uri, int width, Size size) { - super(); - _height = height; - setTitle(title); - setUri(uri); - _width = width; - _size = size; - } - - public void copyOf(Image image) { - _uri.copyFrom(image._uri); - _title.copyFrom(image._title); - setWidth(image.getWidth()); - setHeight(image.getHeight()); - setSize(image.getSize()); - } - - public void clear() { - _uri.clear(); - _title.clear(); - _width = 0; - _height = 0; - _size = null; - } - - - public void writeTo(ByteBuffer bb) { - write(bb, _uri); - write(bb, _title); - write(bb, _width); - write(bb, _height); - write(bb, _size); - } - - public void readFrom(ByteBuffer bb) { - _uri.readFrom(bb); - _title.readFrom(bb); - _width = readInt(bb); - _height = readInt(bb); - _size = SIZES[readOrdinal(bb)]; - } - - public String getUri() { - return _uri.toString(); - } - - public void setUri(CharSequence uri) { - _uri.copyFrom(uri); - } - - public String getTitle() { - return _title.toString(); - } - - public void setTitle(CharSequence title) { - _title.copyFrom(title); - } - - public int getWidth() { - return _width; - } - - public void setWidth(int width) { - _width = width; - } - - public int getHeight() { - return _height; - } - - public void setHeight(int height) { - _height = height; - } - - public Size getSize() { - return _size; - } - - public void setSize(Size size) { - this._size = size; - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + _height; - result = prime * result + ((_size == null) ? 0 : _size.hashCode()); - result = prime * result + _title.hashCode(); - result = prime * result + _uri.hashCode(); - result = prime * result + _width; - return result; - } - - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Image other = (Image) obj; - if (_height != other._height) return false; - if (_size == null) { - if (other._size != null) return false; - } else if (!_size.equals(other._size)) return false; - if (_title == null) { - if (other._title != null) return false; - } else if (!_title.equals(other._title)) return false; - if (_uri == null) { - if (other._uri != null) return false; - } else if (!_uri.equals(other._uri)) return false; - if (_width != other._width) return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Image "); - sb.append("width=").append(_width); - sb.append(", height=").append(_height); - sb.append(", uri=").append(_uri); - sb.append(", title=").append(_title); - sb.append(", size=").append(_size); - sb.append("]"); - return sb.toString(); - } -} diff --git a/src/main/java/com/google/code/java/core/bytebuffer/Media.java b/src/main/java/com/google/code/java/core/bytebuffer/Media.java deleted file mode 100644 index 16c3d8c..0000000 --- a/src/main/java/com/google/code/java/core/bytebuffer/Media.java +++ /dev/null @@ -1,271 +0,0 @@ -package com.google.code.java.core.bytebuffer; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import static com.google.code.java.core.bytebuffer.ByteBuffers.*; - -public class Media { - public enum Player { - JAVA, FLASH; - } - - private static final Player[] PLAYERS = Player.values(); - - private Player _player; - private final AsciiText _uri = new AsciiText(); - private final AsciiText _title = new AsciiText(); - private int _width; - private int _height; - private final AsciiText _format = new AsciiText(); - private long _duration; - private long _size; - private int _bitrate; - private final List _persons = new ArrayList(); - private int _personCount = 0; - private final AsciiText _copyright = new AsciiText(); - - public Media() { - } - - public Media(String copyright, - String format, - Player player, - String title, - String uri, - long duration, - long size, - int height, - int width, - int bitrate) { - setCopyright(copyright); - _duration = duration; - setFormat(format); - _height = height; - _player = player; - _size = size; - setTitle(title); - setUri(uri); - _width = width; - _bitrate = bitrate; - } - - public void clear() { - _player = null; - _uri.clear(); - _title.clear(); - _width = 0; - _height = 0; - _format.clear(); - _duration = 0; - _size = 0; - _personCount = 0; - _copyright.clear(); - } - - public void writeTo(ByteBuffer bb) { - write(bb, _player); - write(bb, _uri); - write(bb, _title); - write(bb, _width); - write(bb, _height); - write(bb, _format); - write(bb, _duration); - write(bb, _size); - write(bb, _bitrate); - write(bb, _personCount); - for (int i = 0; i < _personCount; i++) { - write(bb, _persons.get(i)); - } - write(bb, _copyright); - } - - public void readFrom(ByteBuffer bb) { - _player = PLAYERS[readOrdinal(bb)]; - _uri.readFrom(bb); - _title.readFrom(bb); - _width = readInt(bb); - _height = readInt(bb); - _format.readFrom(bb); - _duration = readLong(bb); - _size = readLong(bb); - _bitrate = readInt(bb); - _personCount = readInt(bb); - for (int i = 0; i < _personCount; i++) - acquirePerson(i).readFrom(bb); - write(bb, _copyright); - } - - private AsciiText acquirePerson(int index) { - while (_persons.size() <= index) - _persons.add(new AsciiText()); - return _persons.get(index); - } - - public Player getPlayer() { - return _player; - } - - public void setPlayer(Player player) { - _player = player; - } - - public String getUri() { - return _uri.toString(); - } - - public void setUri(CharSequence uri) { - _uri.copyFrom(uri); - } - - public String getTitle() { - return _title.toString(); - } - - public void setTitle(CharSequence title) { - _title.copyFrom(title); - } - - public int getWidth() { - return _width; - } - - public void setWidth(int width) { - _width = width; - } - - public int getHeight() { - return _height; - } - - public void setHeight(int height) { - _height = height; - } - - public String getFormat() { - return _format.toString(); - } - - public void setFormat(CharSequence format) { - _format.copyFrom(format); - } - - public long getDuration() { - return _duration; - } - - public void setDuration(long duration) { - _duration = duration; - } - - public long getSize() { - return _size; - } - - public void setSize(long size) { - _size = size; - } - - public int getBitrate() { - return _bitrate; - } - - public void setBitrate(int bitrate) { - this._bitrate = bitrate; - } - - public List getPersons() { - return (List) _persons.subList(0, _personCount); - } - - public void setPersons(List p) { - _personCount = p.size(); - for (int i = 0; i < p.size(); i++) - setPerson(i, p.get(i)); - } - - private void setPerson(int index, CharSequence name) { - while (_persons.size() <= index) _persons.add(new AsciiText()); - _persons.get(index).copyFrom(name); - } - - public void addToPerson(CharSequence person) { - setPerson(_personCount++, person); - } - - public String getCopyright() { - return _copyright.toString(); - } - - public void setCopyright(CharSequence copyright) { - _copyright.copyFrom(copyright); - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + _bitrate; - result = prime * result + _copyright.hashCode(); - result = prime * result + (int) (_duration ^ (_duration >>> 32)); - result = prime * result + _format.hashCode(); - result = prime * result + _height; - result = prime * result + getPersons().hashCode(); - result = prime * result + _player.hashCode(); - result = prime * result + (int) (_size ^ (_size >>> 32)); - result = prime * result + _title.hashCode(); - result = prime * result + _uri.hashCode(); - result = prime * result + _width; - return result; - } - - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - Media other = (Media) obj; - if (_bitrate != other._bitrate) return false; - if (_copyright == null) { - if (other._copyright != null) return false; - } else if (!_copyright.equals(other._copyright)) return false; - if (_duration != other._duration) return false; - if (_format == null) { - if (other._format != null) return false; - } else if (!_format.equals(other._format)) return false; - if (_height != other._height) return false; - if (_persons == null) { - if (other._persons != null) return false; - } else if (!getPersons().equals(other.getPersons())) return false; - if (_player == null) { - if (other._player != null) return false; - } else if (!_player.equals(other._player)) return false; - if (_size != other._size) return false; - if (_title == null) { - if (other._title != null) return false; - } else if (!_title.equals(other._title)) return false; - if (_uri == null) { - if (other._uri != null) return false; - } else if (!_uri.equals(other._uri)) return false; - if (_width != other._width) return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[Media "); - sb.append("width=").append(_width); - sb.append(", height=").append(_height); - sb.append(", duration=").append(_duration); - sb.append(", size=").append(_size); - sb.append(", bitrate=").append(_bitrate); - sb.append(", player=").append(_player); - sb.append(", uri=").append(_uri); - sb.append(", title=").append(_title); - sb.append(", format=").append(_format); - sb.append(", persons=").append(getPersons()); - sb.append(", copyright=").append(_copyright.toString()); - sb.append("]"); - return sb.toString(); - } -} diff --git a/src/main/java/com/google/code/java/core/bytebuffer/MediaContent.java b/src/main/java/com/google/code/java/core/bytebuffer/MediaContent.java deleted file mode 100644 index b04992c..0000000 --- a/src/main/java/com/google/code/java/core/bytebuffer/MediaContent.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.google.code.java.core.bytebuffer; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -import static com.google.code.java.core.bytebuffer.ByteBuffers.readInt; -import static com.google.code.java.core.bytebuffer.ByteBuffers.write; - -public class MediaContent { - private final List _images = new ArrayList(); - private int _imageCount = 0; - private final Media _media; - - public MediaContent() { - this(new Media()); - } - - public MediaContent(Media media) { - this._media = media; - } - - public void clear() { - for (Image image : _images) { - image.clear(); - } - _imageCount = 0; - _media.clear(); - } - - public void writeTo(ByteBuffer bb) { - write(bb, _imageCount); - for (int i = 0; i < _imageCount; i++) - _images.get(i).writeTo(bb); - _media.writeTo(bb); - } - - public void readFrom(ByteBuffer bb) { - _imageCount = readInt(bb); - for (int i = 0; i < _imageCount; i++) - acquireImage(i).readFrom(bb); - _media.readFrom(bb); - } - - public Image acquireImage(int index) { - while (_images.size() <= index) { - _images.add(new Image()); - } - if (index >= _imageCount) - _imageCount = index + 1; - return _images.get(index); - } - - public int imageCount() { - return _imageCount; - } - - public Media getMedia() { - return _media; - } - - public List getImages() { - return _images.subList(0, _imageCount); - } - - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + getImages().hashCode(); - result = prime * result + _media.hashCode(); - return result; - } - - public boolean equals(Object obj) { - if (this == obj) return true; - if (obj == null) return false; - if (getClass() != obj.getClass()) return false; - MediaContent other = (MediaContent) obj; - if (_images == null) { - if (other._images != null) return false; - } else if (!getImages().equals(other.getImages())) return false; - if (_media == null) { - if (other._media != null) return false; - } else if (!_media.equals(other._media)) return false; - return true; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("[MediaContent: "); - sb.append("media=").append(_media); - sb.append(", images=").append(getImages()); - sb.append("]"); - return sb.toString(); - } - - public void addImage(Image image) { - acquireImage(_imageCount++).copyOf(image); - } -} diff --git a/src/main/java/com/google/code/java/core/classloader/LoadAndUnloadMain.java b/src/main/java/com/google/code/java/core/classloader/LoadAndUnloadMain.java deleted file mode 100644 index 8ad2f4e..0000000 --- a/src/main/java/com/google/code/java/core/classloader/LoadAndUnloadMain.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.classloader; - -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; - -public class LoadAndUnloadMain { - public static void main(String... args) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InterruptedException { - URL url = LoadAndUnloadMain.class.getProtectionDomain().getCodeSource().getLocation(); - final String className = LoadAndUnloadMain.class.getPackage().getName() + ".UtilityClass"; - { - ClassLoader cl; - Class clazz; - - for (int i = 0; i < 2; i++) { - cl = new CustomClassLoader(url); - clazz = cl.loadClass(className); - loadClass(clazz); - - cl = new CustomClassLoader(url); - clazz = cl.loadClass(className); - loadClass(clazz); - triggerGC(); - } - } - triggerGC(); - } - - private static void triggerGC() throws InterruptedException { - System.out.println("\n-- Starting GC"); - System.gc(); - Thread.sleep(100); - System.out.println("-- End of GC\n"); - } - - private static void loadClass(Class clazz) throws NoSuchFieldException, IllegalAccessException { - final Field id = clazz.getDeclaredField("ID"); - id.setAccessible(true); - id.get(null); - } - - private static class CustomClassLoader extends URLClassLoader { - public CustomClassLoader(URL url) { - super(new URL[]{url}, null); - } - - @Override - protected Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - try { - return super.loadClass(name, resolve); - } catch (ClassNotFoundException e) { - return Class.forName(name, resolve, LoadAndUnloadMain.class.getClassLoader()); - } - } - - } -} - -class UtilityClass { - static final String ID = Integer.toHexString(System.identityHashCode(UtilityClass.class)); - private static final Object FINAL = new Object() { - @Override - protected void finalize() throws Throwable { - super.finalize(); - System.out.println(ID + " Finalized."); - } - }; - - static { - System.out.println(ID + " Initialising"); - } -} diff --git a/src/main/java/com/google/code/java/core/classloader/ShortClassLoadingMain.java b/src/main/java/com/google/code/java/core/classloader/ShortClassLoadingMain.java deleted file mode 100644 index 7a78f4e..0000000 --- a/src/main/java/com/google/code/java/core/classloader/ShortClassLoadingMain.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.classloader; - -public class ShortClassLoadingMain { - public static void main(String... args) { - System.out.println("Start"); - Class aClass = AClass.class; - System.out.println("Loaded"); - String s = AClass.ID; - System.out.println("Initialised"); - } -} - -class AClass { - static final String ID; - - static { - System.out.println("AClass: Initialising"); - ID = "ID"; - } -} diff --git a/src/main/java/com/google/code/java/core/humanreadablebinary/ComparingHumanReadableToBinaryMain.java b/src/main/java/com/google/code/java/core/humanreadablebinary/ComparingHumanReadableToBinaryMain.java deleted file mode 100644 index a286f5a..0000000 --- a/src/main/java/com/google/code/java/core/humanreadablebinary/ComparingHumanReadableToBinaryMain.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.humanreadablebinary; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.util.ArrayList; -import java.util.List; - -public class ComparingHumanReadableToBinaryMain { - public static void main(String... args) throws IOException { - List longs = new ArrayList(); - for (long i = -1; i <= 10; i++) - longs.add(i); - String asText = longs.toString(); - byte[] bytes1 = asText.getBytes(); - System.out.println("As text: " + bytes1.length + " bytes long, " + asText); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ObjectOutputStream oos = new ObjectOutputStream(baos); - oos.writeObject(longs); - oos.close(); - byte[] bytes2 = baos.toByteArray(); - System.out.println("As binary: " + bytes2.length + " bytes long, " - + new String(bytes2, 0).replaceAll("[^\\p{Graph}]", ".")); - } -} diff --git a/src/main/java/com/google/code/java/core/io/Factory.java b/src/main/java/com/google/code/java/core/io/Factory.java deleted file mode 100644 index 16393b5..0000000 --- a/src/main/java/com/google/code/java/core/io/Factory.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.google.code.java.core.io; - -/** - * @author peter.lawrey - */ -public interface Factory { - public T create(); -} diff --git a/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeA.java b/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeA.java deleted file mode 100644 index 188dd01..0000000 --- a/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeA.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.javac.generated; - -public class CovariantReturnTypeA { - public Object method() { - return 1L; - } -} diff --git a/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeB.java b/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeB.java deleted file mode 100644 index ddc37fc..0000000 --- a/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeB.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.javac.generated; - -public class CovariantReturnTypeB extends CovariantReturnTypeA { - public Number method() { - return 2.0; - } -} diff --git a/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeC.java b/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeC.java deleted file mode 100644 index 2aa4e58..0000000 --- a/src/main/java/com/google/code/java/core/javac/generated/CovariantReturnTypeC.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.javac.generated; - -public class CovariantReturnTypeC extends CovariantReturnTypeB { - public Integer method() { - return 3; - } -} diff --git a/src/main/java/com/google/code/java/core/javac/generated/PrivateField.java b/src/main/java/com/google/code/java/core/javac/generated/PrivateField.java deleted file mode 100644 index 628e440..0000000 --- a/src/main/java/com/google/code/java/core/javac/generated/PrivateField.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.javac.generated; - -public class PrivateField { - private int num = 0; - - public class Inner { - public void set(int n) { - num = n; - } - - public int get() { - return num; - } - - public void increment() { - num++; - } - - public void multiply(int n) { - num *= n; - } - } -} diff --git a/src/main/java/com/google/code/java/core/javac/generated/PrivateMethod.java b/src/main/java/com/google/code/java/core/javac/generated/PrivateMethod.java deleted file mode 100644 index a95c760..0000000 --- a/src/main/java/com/google/code/java/core/javac/generated/PrivateMethod.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.javac.generated; - - -public class PrivateMethod { - private void init() { - throw new UnsupportedOperationException(); - } - - ; - - class Inner { - Inner() { - init(); - } - } - - public static void main(String... args) { - PrivateMethod pm = new PrivateMethod(); - Inner inner = pm.new Inner(); - } -} diff --git a/src/main/java/com/google/code/java/core/micro_optimisation/Example1a.java b/src/main/java/com/google/code/java/core/micro_optimisation/Example1a.java deleted file mode 100644 index 1457932..0000000 --- a/src/main/java/com/google/code/java/core/micro_optimisation/Example1a.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.micro_optimisation; - -public class Example1a { - public static void main(String... args) throws Exception { - long start = System.currentTimeMillis(); - final String hi = "Hello"; - final String all = "World"; - String hi_all = hi + ' ' + all + '!'; - long time = System.currentTimeMillis() - start; - System.out.printf("Creating " + hi_all + " took %,d ms%n", time); - } -} diff --git a/src/main/java/com/google/code/java/core/micro_optimisation/Example1b.java b/src/main/java/com/google/code/java/core/micro_optimisation/Example1b.java deleted file mode 100644 index 3e48c3b..0000000 --- a/src/main/java/com/google/code/java/core/micro_optimisation/Example1b.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.micro_optimisation; - -public class Example1b { - public static void main(String... args) throws Exception { - long start = System.nanoTime(); - final String hi = "Hello"; - final String all = "World"; - String hi_all = hi + ' ' + all + '!'; - long time = System.nanoTime() - start; - System.out.printf("Creating " + hi_all + " took %,d ns%n", time); - } -} diff --git a/src/main/java/com/google/code/java/core/micro_optimisation/Example1c.java b/src/main/java/com/google/code/java/core/micro_optimisation/Example1c.java deleted file mode 100644 index b668f62..0000000 --- a/src/main/java/com/google/code/java/core/micro_optimisation/Example1c.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.micro_optimisation; - -public class Example1c { - public static void main(String... args) throws Exception { - long start = System.nanoTime(); - final int runs = 10000; - String hi_all = null; - for (int i = 0; i < runs; i++) { - final String hi = "Hello"; - final String all = "World"; - hi_all = hi + ' ' + all + '!'; - } - long time = System.nanoTime() - start; - System.out.printf("Creating " + hi_all + " took an average of" + - " %,d ns%n", time / runs); - } -} diff --git a/src/main/java/com/google/code/java/core/micro_optimisation/Example1d.java b/src/main/java/com/google/code/java/core/micro_optimisation/Example1d.java deleted file mode 100644 index 74e8b49..0000000 --- a/src/main/java/com/google/code/java/core/micro_optimisation/Example1d.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.micro_optimisation; - -public class Example1d { - public static void main(String... args) throws Exception { - long start = System.nanoTime(); - final int runs = 1000000; - String hi_all = null; - for (int i = 0; i < runs; i++) { - final String hi = "Hello"; - final String all = "World"; - hi_all = hi + ' ' + all + '!'; - } - long time = System.nanoTime() - start; - System.out.printf("Creating " + hi_all + " took an average of" + - " %.1f ns%n", (double) time / runs); - } -} diff --git a/src/main/java/com/google/code/java/core/micro_optimisation/Example1e.java b/src/main/java/com/google/code/java/core/micro_optimisation/Example1e.java deleted file mode 100644 index 2088cba..0000000 --- a/src/main/java/com/google/code/java/core/micro_optimisation/Example1e.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.micro_optimisation; - -public class Example1e { - public static void main(String... args) throws Exception { - long start = 0; - final int runs = 1000000000; - String hi_all = null; - for (int i = -11000; i < runs; i++) { - if (i == 0) start = System.nanoTime(); - final String hi = "Hello"; - final String all = "World"; - hi_all = hi + ' ' + all + '!'; - } - long time = System.nanoTime() - start; - System.out.printf("Creating " + hi_all + " took an average of" + - " %.2f ns%n", (double) time / runs); - } -} diff --git a/src/main/java/com/google/code/java/core/micro_optimisation/Example1f.java b/src/main/java/com/google/code/java/core/micro_optimisation/Example1f.java deleted file mode 100644 index 0f697c7..0000000 --- a/src/main/java/com/google/code/java/core/micro_optimisation/Example1f.java +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.micro_optimisation; - -public class Example1f { - public static void main(String... args) throws Exception { - long start = 0; - final int runs = 100000000; - String hi_all = null; - for (int i = -11000; i < runs; i++) { - if (i == 0) start = System.nanoTime(); - String hi = "Hello"; - String all = "World"; - hi_all = hi + ' ' + all + '!'; - } - long time = System.nanoTime() - start; - System.out.printf("Creating " + hi_all + " took an average of" + - " %.2f ns%n", (double) time / runs); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferDoubleReader.java b/src/main/java/com/google/code/java/core/parser/ByteBufferDoubleReader.java deleted file mode 100644 index dd8a710..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferDoubleReader.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; - -public class ByteBufferDoubleReader implements DoubleReader { - private final ByteBuffer buffer; - - public ByteBufferDoubleReader(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public double read() throws BufferUnderflowException { - return buffer.getDouble(); - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferDoubleWriter.java b/src/main/java/com/google/code/java/core/parser/ByteBufferDoubleWriter.java deleted file mode 100644 index 69f337c..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferDoubleWriter.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; - -public class ByteBufferDoubleWriter implements DoubleWriter { - protected final ByteBuffer buffer; - - public ByteBufferDoubleWriter(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void write(double num) throws BufferOverflowException { - buffer.putDouble(num); - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferFixedWriter.java b/src/main/java/com/google/code/java/core/parser/ByteBufferFixedWriter.java deleted file mode 100644 index cacf20f..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferFixedWriter.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; - -public class ByteBufferFixedWriter extends ByteBufferTextDoubleWriter { - private final long factor; - private long maxFactor; - private long maxValue; - - public ByteBufferFixedWriter(ByteBuffer buffer, int precision) { - super(buffer); - factor = ParserUtils.TENS[precision]; - maxValue = 1L << 53 / factor; - } - - @Override - public void write(double num) throws BufferOverflowException { - if (Math.abs(num) < maxValue) - write0(num); - else - super.write(num); - } - - private void write0(double num) { - if (num < 0) { - writeByte('-'); - num = -num; - } else if (num == 0) { - writeByte('0'); - writeByte(SEPARATOR); - return; - } - maxFactor = Long.MAX_VALUE / factor; - long factor = this.factor; - if (num > maxFactor) { - while (factor > 1 && num > Long.MAX_VALUE / factor) - factor /= 10; - } - long value = (long) (num * factor + 0.5); - while (factor > 1 && value % 10 == 0) { - factor /= 10; - value /= 10; - } - if (factor == 1) { - writeLong(value); - writeByte(SEPARATOR); - return; - } - - int digits = ParserUtils.digits(value); - int factorDigits = ParserUtils.digits(factor); - if (digits < factorDigits) - digits = factorDigits; - final int position = buffer.position(); - for (int i = digits; i >= 0; i--) { - if (factorDigits == 1) { - buffer.put(position + i, (byte) '.'); - factorDigits = 0; - } else { - buffer.put(position + i, (byte) ('0' + value % 10)); - value /= 10; - factorDigits--; - } - } - buffer.position(position + digits + 1); - writeByte(SEPARATOR); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferLongReader.java b/src/main/java/com/google/code/java/core/parser/ByteBufferLongReader.java deleted file mode 100644 index b8ea496..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferLongReader.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; - -public class ByteBufferLongReader implements LongReader { - private final ByteBuffer buffer; - - public ByteBufferLongReader(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public long read() throws BufferUnderflowException { - return buffer.getLong(); - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferLongWriter.java b/src/main/java/com/google/code/java/core/parser/ByteBufferLongWriter.java deleted file mode 100644 index bafd459..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferLongWriter.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; - -public class ByteBufferLongWriter implements LongWriter { - private final ByteBuffer buffer; - - public ByteBufferLongWriter(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void write(long num) throws BufferOverflowException { - buffer.putLong(num); - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferTextDoubleReader.java b/src/main/java/com/google/code/java/core/parser/ByteBufferTextDoubleReader.java deleted file mode 100644 index d0cbdb0..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferTextDoubleReader.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; - -public class ByteBufferTextDoubleReader implements DoubleReader { - public static final long MAX_VALUE_DIVIDE_10 = Long.MAX_VALUE / 10; - private final ByteBuffer buffer; - - public ByteBufferTextDoubleReader(ByteBuffer buffer) { - this.buffer = buffer; - } - - static double asDouble(long value, int exp, boolean negative, int decimalPlaces) { - if (decimalPlaces > 0 && value < Long.MAX_VALUE / 2) { - if (value < Long.MAX_VALUE / (1L << 32)) { - exp -= 32; - value <<= 32; - } - if (value < Long.MAX_VALUE / (1L << 16)) { - exp -= 16; - value <<= 16; - } - if (value < Long.MAX_VALUE / (1L << 8)) { - exp -= 8; - value <<= 8; - } - if (value < Long.MAX_VALUE / (1L << 4)) { - exp -= 4; - value <<= 4; - } - if (value < Long.MAX_VALUE / (1L << 2)) { - exp -= 2; - value <<= 2; - } - if (value < Long.MAX_VALUE / (1L << 1)) { - exp -= 1; - value <<= 1; - } - } - for (; decimalPlaces > 0; decimalPlaces--) { - exp--; - long mod = value % 5; - value /= 5; - int modDiv = 1; - if (value < Long.MAX_VALUE / (1L << 4)) { - exp -= 4; - value <<= 4; - modDiv <<= 4; - } - if (value < Long.MAX_VALUE / (1L << 2)) { - exp -= 2; - value <<= 2; - modDiv <<= 2; - } - if (value < Long.MAX_VALUE / (1L << 1)) { - exp -= 1; - value <<= 1; - modDiv <<= 1; - } - value += modDiv * mod / 5; - } - final double d = Math.scalb((double) value, exp); - return negative ? -d : d; - } - - @Override - public double read() throws BufferUnderflowException { - long value = 0; - int exp = 0; - boolean negative = false; - int decimalPlaces = Integer.MIN_VALUE; - while (true) { - byte ch = buffer.get(); - if (ch >= '0' && ch <= '9') { - while (value >= MAX_VALUE_DIVIDE_10) { - value >>>= 1; - exp++; - } - value = value * 10 + (ch - '0'); - decimalPlaces++; - } else if (ch == '-') { - negative = true; - } else if (ch == '.') { - decimalPlaces = 0; - } else { - break; - } - } - - return asDouble(value, exp, negative, decimalPlaces); - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferTextDoubleWriter.java b/src/main/java/com/google/code/java/core/parser/ByteBufferTextDoubleWriter.java deleted file mode 100644 index 91e5847..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferTextDoubleWriter.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; - -public class ByteBufferTextDoubleWriter implements DoubleWriter { - private static final long MAX_VALUE_DIVIDE_5 = Long.MAX_VALUE / 5; - protected static final char SEPARATOR = '\n'; - private static final long MAX_DECIMALS = 1L << 53; - private static final byte[] Infinity = "Infinity".getBytes(); - private static final byte[] NaN = "NaN".getBytes(); - - protected final ByteBuffer buffer; - - public ByteBufferTextDoubleWriter(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void write(double d) throws BufferOverflowException { - long val = Double.doubleToRawLongBits(d); - int sign = (int) (val >>> 63); - int exp = (int) ((val >>> 52) & 2047); - long mantissa = val & ((1L << 52) - 1); - if (sign != 0) { - writeByte('-'); - } - if (exp == 0 && mantissa == 0) { - writeByte('0'); - writeByte(SEPARATOR); - return; - } else if (exp == 2047) { - if (mantissa == 0) { - buffer.put(Infinity); - writeByte(SEPARATOR); - } else { - buffer.put(NaN); - writeByte(SEPARATOR); - } - return; - } else if (exp > 0) { - mantissa += 1L << 52; - } - final int shift = (1023 + 52) - exp; - if (shift > 0) { - // integer and faction - if (shift < 53) { - long intValue = mantissa >> shift; - writeLong(intValue); - mantissa -= intValue << shift; - if (mantissa > 0) { - writeByte('.'); - mantissa <<= 1; - mantissa++; - int precision = shift + 1; - long error = 1; - - long value = intValue; - int decimalPlaces = 0; - while (mantissa > error) { - // times 5*2 = 10 - mantissa *= 5; - error *= 5; - precision--; - long num = (mantissa >> precision); - value = value * 10 + num; - writeByte((char) ('0' + num)); - mantissa -= num << precision; - - final double parsedValue = ByteBufferTextDoubleReader.asDouble(value, 0, sign != 0, ++decimalPlaces); - if (parsedValue == d) - break; - } - } - writeByte(SEPARATOR); - return; - } else { - // faction. - writeByte('0'); - writeByte('.'); - mantissa <<= 6; - mantissa += (1 << 5); - int precision = shift + 6; - - long error = (1 << 5); - - long value = 0; - int decimalPlaces = 0; - while (mantissa > error) { - while (mantissa > MAX_VALUE_DIVIDE_5) { - mantissa >>>= 1; - error = (error + 1) >>> 1; - precision--; - } - // times 5*2 = 10 - mantissa *= 5; - error *= 5; - precision--; - if (precision >= 64) { - decimalPlaces++; - writeByte('0'); - continue; - } - long num = (mantissa >>> precision); - value = value * 10 + num; - final char c = (char) ('0' + num); - assert !(c < '0' || c > '9'); - writeByte(c); - mantissa -= num << precision; - final double parsedValue = ByteBufferTextDoubleReader.asDouble(value, 0, sign != 0, ++decimalPlaces); - if (parsedValue == d) - break; - } - writeByte(SEPARATOR); - return; - } - } - // large number - mantissa <<= 10; - int precision = -10 - shift; - int digits = 0; - while ((precision > 53 || mantissa > Long.MAX_VALUE >> precision) && precision > 0) { - digits++; - precision--; - long mod = mantissa % 5; - mantissa /= 5; - int modDiv = 1; - while (mantissa < MAX_VALUE_DIVIDE_5 && precision > 1) { - precision -= 1; - mantissa <<= 1; - modDiv <<= 1; - } - mantissa += modDiv * mod / 5; - } - long val2 = precision > 0 ? mantissa << precision : mantissa >>> -precision; - - writeLong(val2); - for (int i = 0; i < digits; i++) - writeByte('0'); - writeByte(SEPARATOR); - return; - } - - protected void writeLong(long val2) { - int digits = ParserUtils.digits(val2); - // starting from the end, write each digit - for (int i = digits - 1; i >= 0; i--) { - // write the lowest digit. - buffer.put(buffer.position() + i, (byte) (val2 % 10 + '0')); - // remove that digit. - val2 /= 10; - } - assert val2 == 0; - // move the position to after the digits. - buffer.position(buffer.position() + digits); - } - - protected void writeByte(long c) { - buffer.put((byte) c); - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferTextLongReader.java b/src/main/java/com/google/code/java/core/parser/ByteBufferTextLongReader.java deleted file mode 100644 index 101f70e..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferTextLongReader.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; - -public class ByteBufferTextLongReader implements LongReader { - private final ByteBuffer buffer; - - public ByteBufferTextLongReader(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public long read() throws BufferUnderflowException { - long num = 0; - boolean negative = false; - while (true) { - byte b = buffer.get(); -// if (b >= '0' && b <= '9') - if ((b - ('0' + Integer.MIN_VALUE)) <= 9 + Integer.MIN_VALUE) - num = num * 10 + b - '0'; - else if (b == '-') - negative = true; - else - break; - } - return negative ? -num : num; - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/ByteBufferTextLongWriter.java b/src/main/java/com/google/code/java/core/parser/ByteBufferTextLongWriter.java deleted file mode 100644 index a71dcf4..0000000 --- a/src/main/java/com/google/code/java/core/parser/ByteBufferTextLongWriter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.nio.BufferOverflowException; -import java.nio.ByteBuffer; - -public class ByteBufferTextLongWriter implements LongWriter { - private static final byte[] MIN_VALUE_TEXT = Long.toString(Long.MIN_VALUE).getBytes(); - public static final char SEPARATOR = '\n'; - private final ByteBuffer buffer; - - public ByteBufferTextLongWriter(ByteBuffer buffer) { - this.buffer = buffer; - } - - @Override - public void write(long num) throws BufferOverflowException { - if (num < 0) { - if (num == Long.MIN_VALUE) { - buffer.put(MIN_VALUE_TEXT); - return; - } - writeByte('-'); - num = -num; - } - if (num == 0) { - writeByte('0'); - writeByte(SEPARATOR); - } else { - // find the number of digits - int digits = ParserUtils.digits(num); - // starting from the end, write each digit - for (int i = digits - 1; i >= 0; i--) { - // write the lowest digit. - buffer.put(buffer.position() + i, (byte) (num % 10 + '0')); - // remove that digit. - num /= 10; - } - // move the position to after the digits. - buffer.position(buffer.position() + digits); - writeByte(SEPARATOR); - } - } - - private void writeByte(int c) { - buffer.put((byte) c); - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DataDoubleReader.java b/src/main/java/com/google/code/java/core/parser/DataDoubleReader.java deleted file mode 100644 index d873a1c..0000000 --- a/src/main/java/com/google/code/java/core/parser/DataDoubleReader.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; - -public class DataDoubleReader implements DoubleReader { - private final DataInputStream in; - - public DataDoubleReader(InputStream in) { - this.in = new DataInputStream(new BufferedInputStream(in)); - } - - public double read() throws IOException { - return in.readDouble(); - } - - public void close() { - ParserUtils.close(in); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DataDoubleWriter.java b/src/main/java/com/google/code/java/core/parser/DataDoubleWriter.java deleted file mode 100644 index c561b69..0000000 --- a/src/main/java/com/google/code/java/core/parser/DataDoubleWriter.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class DataDoubleWriter implements DoubleWriter { - private final DataOutputStream out; - - public DataDoubleWriter(OutputStream os) { - this.out = new DataOutputStream(new BufferedOutputStream(os)); - } - - @Override - public void write(double num) throws IOException { - out.writeDouble(num); - } - - @Override - public void close() { - ParserUtils.close(out); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DataLongReader.java b/src/main/java/com/google/code/java/core/parser/DataLongReader.java deleted file mode 100644 index 52c11f6..0000000 --- a/src/main/java/com/google/code/java/core/parser/DataLongReader.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedInputStream; -import java.io.DataInputStream; -import java.io.IOException; -import java.io.InputStream; - -public class DataLongReader implements LongReader { - private final DataInputStream in; - - public DataLongReader(InputStream in) { - this.in = new DataInputStream(new BufferedInputStream(in)); - } - - public long read() throws IOException { - return in.readLong(); - } - - public void close() { - ParserUtils.close(in); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DataLongWriter.java b/src/main/java/com/google/code/java/core/parser/DataLongWriter.java deleted file mode 100644 index 48b3b94..0000000 --- a/src/main/java/com/google/code/java/core/parser/DataLongWriter.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedOutputStream; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class DataLongWriter implements LongWriter { - private final DataOutputStream out; - - public DataLongWriter(OutputStream os) { - this.out = new DataOutputStream(new BufferedOutputStream(os)); - } - - @Override - public void write(long num) throws IOException { - out.writeLong(num); - } - - @Override - public void close() { - ParserUtils.close(out); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DecimalFormatDoubleReader.java b/src/main/java/com/google/code/java/core/parser/DecimalFormatDoubleReader.java deleted file mode 100644 index 55656a8..0000000 --- a/src/main/java/com/google/code/java/core/parser/DecimalFormatDoubleReader.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedReader; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.ParseException; - -public class DecimalFormatDoubleReader implements DoubleReader { - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0"); - private final BufferedReader br; - - public DecimalFormatDoubleReader(BufferedReader br) { - this.br = br; - } - - @Override - public double read() throws IOException { - String num = null; - try { - num = br.readLine(); - return DECIMAL_FORMAT.parse(num).doubleValue(); - } catch (ParseException e) { - throw new IOException("Unable to parse '" + num + '\'', e); - } - } - - @Override - public void close() { - ParserUtils.close(br); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DecimalFormatDoubleWriter.java b/src/main/java/com/google/code/java/core/parser/DecimalFormatDoubleWriter.java deleted file mode 100644 index 8074086..0000000 --- a/src/main/java/com/google/code/java/core/parser/DecimalFormatDoubleWriter.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.PrintWriter; -import java.text.DecimalFormat; - -public class DecimalFormatDoubleWriter implements DoubleWriter { - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.0"); - private final PrintWriter pw; - - public DecimalFormatDoubleWriter(PrintWriter pw) { - this.pw = pw; - } - - @Override - public void write(double num) { - pw.println(DECIMAL_FORMAT.format(num)); - } - - @Override - public void close() { - pw.close(); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DecimalFormatLongReader.java b/src/main/java/com/google/code/java/core/parser/DecimalFormatLongReader.java deleted file mode 100644 index 0b6b3f3..0000000 --- a/src/main/java/com/google/code/java/core/parser/DecimalFormatLongReader.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedReader; -import java.io.IOException; -import java.text.DecimalFormat; -import java.text.ParseException; - -public class DecimalFormatLongReader implements LongReader { - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0"); - private final BufferedReader br; - - public DecimalFormatLongReader(BufferedReader br) { - this.br = br; - } - - @Override - public long read() throws IOException { - String num = null; - try { - num = br.readLine(); - return DECIMAL_FORMAT.parse(num).longValue(); - } catch (ParseException e) { - throw new IOException("Unable to parse '" + num + '\'', e); - } - } - - @Override - public void close() { - ParserUtils.close(br); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DecimalFormatLongWriter.java b/src/main/java/com/google/code/java/core/parser/DecimalFormatLongWriter.java deleted file mode 100644 index d0eaf4a..0000000 --- a/src/main/java/com/google/code/java/core/parser/DecimalFormatLongWriter.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.PrintWriter; -import java.text.DecimalFormat; - -public class DecimalFormatLongWriter implements LongWriter { - private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0"); - private final PrintWriter pw; - - public DecimalFormatLongWriter(PrintWriter pw) { - this.pw = pw; - } - - @Override - public void write(long num) { - pw.println(DECIMAL_FORMAT.format(num)); - } - - @Override - public void close() { - pw.close(); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/DoubleReader.java b/src/main/java/com/google/code/java/core/parser/DoubleReader.java deleted file mode 100644 index baf93c7..0000000 --- a/src/main/java/com/google/code/java/core/parser/DoubleReader.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import java.io.Closeable; -import java.io.IOException; - -public interface DoubleReader extends Closeable { - double read() throws IOException; - - @Override - void close(); -} diff --git a/src/main/java/com/google/code/java/core/parser/DoubleWriter.java b/src/main/java/com/google/code/java/core/parser/DoubleWriter.java deleted file mode 100644 index 0725309..0000000 --- a/src/main/java/com/google/code/java/core/parser/DoubleWriter.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import java.io.Closeable; -import java.io.IOException; - -public interface DoubleWriter extends Closeable { - void write(double num) throws IOException; - - @Override - void close(); -} diff --git a/src/main/java/com/google/code/java/core/parser/LongReader.java b/src/main/java/com/google/code/java/core/parser/LongReader.java deleted file mode 100644 index 154c249..0000000 --- a/src/main/java/com/google/code/java/core/parser/LongReader.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import java.io.Closeable; -import java.io.IOException; - -public interface LongReader extends Closeable { - long read() throws IOException; - - @Override - void close(); -} diff --git a/src/main/java/com/google/code/java/core/parser/LongWriter.java b/src/main/java/com/google/code/java/core/parser/LongWriter.java deleted file mode 100644 index e2b4057..0000000 --- a/src/main/java/com/google/code/java/core/parser/LongWriter.java +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import java.io.Closeable; -import java.io.IOException; - -public interface LongWriter extends Closeable { - void write(long num) throws IOException; - - @Override - void close(); -} diff --git a/src/main/java/com/google/code/java/core/parser/ParserUtils.java b/src/main/java/com/google/code/java/core/parser/ParserUtils.java deleted file mode 100644 index 9fcf051..0000000 --- a/src/main/java/com/google/code/java/core/parser/ParserUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import sun.misc.Unsafe; - -import java.io.Closeable; -import java.io.IOException; -import java.lang.reflect.Field; -import java.util.Arrays; - -public enum ParserUtils { - ; - static final long[] TENS = new long[19]; - - static { - TENS[0] = 1; - for (int i = 1; i < TENS.length; i++) - TENS[i] = TENS[i - 1] * 10; - } - - public static int digits(long l) { - int idx = Arrays.binarySearch(TENS, l); - return idx >= 0 ? idx + 1 : ~idx; - } - - public static void close(Closeable closeable) { - if (closeable != null) try { - closeable.close(); - } catch (IOException ignored) { - } - } - - public static final Unsafe UNSAFE; static { - try { - Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); - theUnsafe.setAccessible(true); - UNSAFE = (Unsafe) theUnsafe.get(null); - } catch (Exception e) { - throw new AssertionError(e); - } - } -} diff --git a/src/main/java/com/google/code/java/core/parser/PrintDoubleReader.java b/src/main/java/com/google/code/java/core/parser/PrintDoubleReader.java deleted file mode 100644 index db8c213..0000000 --- a/src/main/java/com/google/code/java/core/parser/PrintDoubleReader.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedReader; -import java.io.IOException; - -public class PrintDoubleReader implements DoubleReader { - private final BufferedReader br; - - public PrintDoubleReader(BufferedReader br) { - this.br = br; - } - - @Override - public double read() throws IOException, NumberFormatException { - return Double.parseDouble(br.readLine()); - } - - @Override - public void close() { - ParserUtils.close(br); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/PrintDoubleWriter.java b/src/main/java/com/google/code/java/core/parser/PrintDoubleWriter.java deleted file mode 100644 index 83f4f28..0000000 --- a/src/main/java/com/google/code/java/core/parser/PrintDoubleWriter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.PrintWriter; - -public class PrintDoubleWriter implements DoubleWriter { - private final PrintWriter pw; - - public PrintDoubleWriter(PrintWriter pw) { - this.pw = pw; - } - - @Override - public void write(double num) { - pw.println(num); - } - - @Override - public void close() { - pw.close(); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/PrintLongReader.java b/src/main/java/com/google/code/java/core/parser/PrintLongReader.java deleted file mode 100644 index cb7e345..0000000 --- a/src/main/java/com/google/code/java/core/parser/PrintLongReader.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.BufferedReader; -import java.io.IOException; - -public class PrintLongReader implements LongReader { - private final BufferedReader br; - - public PrintLongReader(BufferedReader br) { - this.br = br; - } - - @Override - public long read() throws IOException, NumberFormatException { - return Long.parseLong(br.readLine()); - } - - @Override - public void close() { - ParserUtils.close(br); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/PrintLongWriter.java b/src/main/java/com/google/code/java/core/parser/PrintLongWriter.java deleted file mode 100644 index a9fa4c9..0000000 --- a/src/main/java/com/google/code/java/core/parser/PrintLongWriter.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import java.io.PrintWriter; - -public class PrintLongWriter implements LongWriter { - private final PrintWriter pw; - - public PrintLongWriter(PrintWriter pw) { - this.pw = pw; - } - - @Override - public void write(long num) { - pw.println(num); - } - - @Override - public void close() { - pw.close(); - } -} diff --git a/src/main/java/com/google/code/java/core/parser/UnsafeDoubleReader.java b/src/main/java/com/google/code/java/core/parser/UnsafeDoubleReader.java deleted file mode 100644 index d431954..0000000 --- a/src/main/java/com/google/code/java/core/parser/UnsafeDoubleReader.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -public class UnsafeDoubleReader implements DoubleReader { - private long address; - - public UnsafeDoubleReader(long address) { - this.address = address; - } - - @Override - public double read() { - double num = ParserUtils.UNSAFE.getDouble(address); - address += 8; - return num; - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/UnsafeDoubleWriter.java b/src/main/java/com/google/code/java/core/parser/UnsafeDoubleWriter.java deleted file mode 100644 index 076dac9..0000000 --- a/src/main/java/com/google/code/java/core/parser/UnsafeDoubleWriter.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -public class UnsafeDoubleWriter implements DoubleWriter { - private long address; - - public UnsafeDoubleWriter(long address) { - this.address = address; - } - - @Override - public void write(double num) { - ParserUtils.UNSAFE.putDouble(address, num); - address += 8; - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/parser/UnsafeLongReader.java b/src/main/java/com/google/code/java/core/parser/UnsafeLongReader.java deleted file mode 100644 index 6438d09..0000000 --- a/src/main/java/com/google/code/java/core/parser/UnsafeLongReader.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -public class UnsafeLongReader implements LongReader { - private long address; - - public UnsafeLongReader(long address) { - this.address = address; - } - - @Override - public long read() { - long num = ParserUtils.UNSAFE.getLong(address); - address += 8; - return num; - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/UnsafeLongWriter.java b/src/main/java/com/google/code/java/core/parser/UnsafeLongWriter.java deleted file mode 100644 index 2aafab5..0000000 --- a/src/main/java/com/google/code/java/core/parser/UnsafeLongWriter.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -public class UnsafeLongWriter implements LongWriter { - private long address; - - public UnsafeLongWriter(long address) { - this.address = address; - } - - @Override - public void write(long num) { - ParserUtils.UNSAFE.putLong(address, num); - address += 8; - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/parser/UnsafeTextLongReader.java b/src/main/java/com/google/code/java/core/parser/UnsafeTextLongReader.java deleted file mode 100644 index d7d5120..0000000 --- a/src/main/java/com/google/code/java/core/parser/UnsafeTextLongReader.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -public class UnsafeTextLongReader implements LongReader { - private long address; - - public UnsafeTextLongReader(long address) { - this.address = address; - } - - @Override - public long read() { - long num = 0; - boolean negative = false; - while (true) { - byte b = ParserUtils.UNSAFE.getByte(address++); -// if (b >= '0' && b <= '9') - if ((b - ('0' + Integer.MIN_VALUE)) <= 9 + Integer.MIN_VALUE) - num = num * 10 + b - '0'; - else if (b == '-') - negative = true; - else - break; - } - return negative ? -num : num; - } - - @Override - public void close() { - } -} diff --git a/src/main/java/com/google/code/java/core/parser/UnsafeTextLongWriter.java b/src/main/java/com/google/code/java/core/parser/UnsafeTextLongWriter.java deleted file mode 100644 index 025940b..0000000 --- a/src/main/java/com/google/code/java/core/parser/UnsafeTextLongWriter.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -public class UnsafeTextLongWriter implements LongWriter { - private static final byte[] MIN_VALUE_TEXT = Long.toString(Long.MIN_VALUE).getBytes(); - - private long address; - - public UnsafeTextLongWriter(long address) { - this.address = address; - } - - @Override - public void write(long num) { - if (num < 0) { - if (num == Long.MIN_VALUE) { - for (int i = 0; i < MIN_VALUE_TEXT.length; i++) { - ParserUtils.UNSAFE.putByte(address++, MIN_VALUE_TEXT[i]); - return; - } - } - writeByte('-'); - num = -num; - } - if (num == 0) { - writeByte('0'); - writeByte('\n'); - } else if (num < 10000000) { - int digits = num < 10000 ? num < 100 ? num < 10 ? 1 : 2 : num < 1000 ? 3 : 4 : - num < 1000000 ? num < 100000 ? 5 : 6 : num < 10000000 ? 7 : 8; - // assume little endian. - int shift = 8 * digits; - long val = (long) '\n' << shift; - shift -= 8; - for (int i = 0; i < digits; i++, shift -= 8) { - val |= (long) (num % 10 + '0') << shift; - num /= 10; - } - ParserUtils.UNSAFE.putLong(address, val); - address += digits + 1; - } else { - int digits = ParserUtils.digits(num); - for (int i = digits - 1; i >= 0; i--) { - ParserUtils.UNSAFE.putByte(address + i, (byte) (num % 10 + '0')); - num /= 10; - } - address += digits; - writeByte('\n'); - } - } - - private void writeByte(int c) { - ParserUtils.UNSAFE.putByte(address++, (byte) c); - } - - @Override - public void close() { - - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/PrimitiveFastMapMain.java b/src/main/java/com/google/code/java/core/primitives/PrimitiveFastMapMain.java deleted file mode 100644 index 4443159..0000000 --- a/src/main/java/com/google/code/java/core/primitives/PrimitiveFastMapMain.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import javolution.util.FastMap; - -import java.io.FileNotFoundException; - -public class PrimitiveFastMapMain { - private static final long START = System.currentTimeMillis(); - - public static void main(String... args) throws InterruptedException, FileNotFoundException { - int runs = 1200; - FastMap counters = new FastMap(); - Report out = new Report(runs); - System.gc(); - for (int i = 0; i < runs; i++) { - performTest(out, counters); - Thread.sleep(100); - } - out.print("primitive-fastmap-report.csv"); - } - - private static void performTest(Report out, FastMap counters) { - counters.clear(); - long start = System.nanoTime(); - int runs = 300 * 300; - for (int i = 0; i < runs; i++) { - int x = i % 300; - int y = i / 300; - int times = x * y; - Integer count = counters.get(times); - if (count == null) - counters.put(times, 1); - else - counters.put(times, count + 1); - } - long time = System.nanoTime() - start; - out.usedMB[out.count] = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6; - out.timeFromStart[out.count] = (System.currentTimeMillis() - START) / 1e3; - out.avgTime[out.count] = (double) time / runs; - out.count++; - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/PrimitiveHashMapMain.java b/src/main/java/com/google/code/java/core/primitives/PrimitiveHashMapMain.java deleted file mode 100644 index 924da3b..0000000 --- a/src/main/java/com/google/code/java/core/primitives/PrimitiveHashMapMain.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.Map; - -public class PrimitiveHashMapMain { - private static final long START = System.currentTimeMillis(); - - public static void main(String... args) throws InterruptedException, FileNotFoundException { - int runs = 1200; - Map counters = new HashMap(); - Report out = new Report(runs); - System.gc(); - for (int i = 0; i < runs; i++) { - performTest(out, counters); - Thread.sleep(100); - } - out.print("primitive-hashmap-report.csv"); - } - - private static void performTest(Report out, Map counters) { - counters.clear(); - long start = System.nanoTime(); - int runs = 300 * 300; - for (int i = 0; i < runs; i++) { - int x = i % 300; - int y = i / 300; - int times = x * y; - Integer count = counters.get(times); - if (count == null) - counters.put(times, 1); - else - counters.put(times, count + 1); - } - long time = System.nanoTime() - start; - out.usedMB[out.count] = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6; - out.timeFromStart[out.count] = (System.currentTimeMillis() - START) / 1e3; - out.avgTime[out.count] = (double) time / runs; - out.count++; - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/PrimitiveMain.java b/src/main/java/com/google/code/java/core/primitives/PrimitiveMain.java deleted file mode 100644 index a7a10a9..0000000 --- a/src/main/java/com/google/code/java/core/primitives/PrimitiveMain.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import java.io.FileNotFoundException; - -public class PrimitiveMain { - private static final long START = System.currentTimeMillis(); - - public static void main(String... args) throws InterruptedException, FileNotFoundException { - int runs = 1200; - SimpleIntHashMap counters = new SimpleIntHashMap(); - Report out = new Report(runs); - System.gc(); - for (int i = 0; i < runs; i++) { - performTest(out, counters); - Thread.sleep(100); - } - out.print("primitive-report.csv"); - } - - private static void performTest(Report out, SimpleIntHashMap counters) { - counters.clear(); - long start = System.nanoTime(); - int runs = 300 * 300; - for (int i = 0; i < runs; i++) { - int x = i % 300; - int y = i / 300; - int times = x * y; - int count = counters.get(times); - if (count == SimpleIntHashMap.NO_VALUE) - counters.put(times, 1); - else - counters.put(times, count + 1); - } - long time = System.nanoTime() - start; - out.usedMB[out.count] = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6; - out.timeFromStart[out.count] = (System.currentTimeMillis() - START) / 1e3; - out.avgTime[out.count] = (double) time / runs; - out.count++; - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/PrimitiveTIntIntHashMapMain.java b/src/main/java/com/google/code/java/core/primitives/PrimitiveTIntIntHashMapMain.java deleted file mode 100644 index 3a4cbb6..0000000 --- a/src/main/java/com/google/code/java/core/primitives/PrimitiveTIntIntHashMapMain.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import gnu.trove.TIntIntHashMap; - -import java.io.FileNotFoundException; - -public class PrimitiveTIntIntHashMapMain { - private static final long START = System.currentTimeMillis(); - - public static void main(String... args) throws InterruptedException, FileNotFoundException { - int runs = 1200; - TIntIntHashMap counters = new TIntIntHashMap(); - Report out = new Report(runs); - System.gc(); - for (int i = 0; i < runs; i++) { - performTest(out, counters); - Thread.sleep(100); - } - out.print("primitive-tintinthashmap-report.csv"); - } - - private static void performTest(Report out, TIntIntHashMap counters) { - counters.clear(); - long start = System.nanoTime(); - int runs = 300 * 300; - for (int i = 0; i < runs; i++) { - int x = i % 300; - int y = i / 300; - int times = x * y; - counters.adjustOrPutValue(times, 1, 1); - } - long time = System.nanoTime() - start; - out.usedMB[out.count] = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6; - out.timeFromStart[out.count] = (System.currentTimeMillis() - START) / 1e3; - out.avgTime[out.count] = (double) time / runs; - out.count++; - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/Report.java b/src/main/java/com/google/code/java/core/primitives/Report.java deleted file mode 100644 index 06bebfe..0000000 --- a/src/main/java/com/google/code/java/core/primitives/Report.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import java.io.FileNotFoundException; -import java.io.PrintWriter; - -public class Report { - final double[] usedMB, timeFromStart, avgTime; - int count; - - public Report(int capacity) { - usedMB = new double[capacity]; - timeFromStart = new double[capacity]; - avgTime = new double[capacity]; - } - - void print(String filename) throws FileNotFoundException { - PrintWriter out = new PrintWriter(filename); - for (int i = 0; i < count; i++) - out.printf("%.1f, Took %.1f ns per loop, free MB, %.1f%n", timeFromStart[i], avgTime[i], usedMB[i]); - out.close(); - - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/SimpleIntHashMap.java b/src/main/java/com/google/code/java/core/primitives/SimpleIntHashMap.java deleted file mode 100644 index 964f4e0..0000000 --- a/src/main/java/com/google/code/java/core/primitives/SimpleIntHashMap.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import java.util.Arrays; - -/** - * User: peter - */ -public class SimpleIntHashMap { - public static final int NO_VALUE = Integer.MIN_VALUE; - private int[] keys = new int[16]; { - Arrays.fill(keys, NO_VALUE); - } - - private int[] values = new int[16]; - private int lastKey = keys.length / 2 - 1; - - public int get(int key) { - int hash = key & lastKey; - if (keys[hash] == key) - return values[hash]; - return NO_VALUE; - } - - public void put(int key, int value) { - int hash = key & lastKey; - if (keys[hash] != NO_VALUE && keys[hash] != key) { - resize(); - hash = key & lastKey; - if (keys[hash] != NO_VALUE && keys[hash] != key) - throw new UnsupportedOperationException("Unable to handle collision."); - } - keys[hash] = key; - values[hash] = value; - } - - private void resize() { - int len2 = keys.length * 2; - int[] keys2 = new int[len2]; - Arrays.fill(keys2, NO_VALUE); - int[] values2 = new int[len2]; - lastKey = len2 - 1; - for (int i = 0; i < keys.length; i++) { - int key = keys[i]; - int value = values[i]; - if (key == NO_VALUE) continue; - int hash = key & lastKey; - if (keys2[hash] != NO_VALUE) - throw new UnsupportedOperationException("Unable to handle collision."); - keys2[hash] = key; - values2[hash] = value; - } - keys = keys2; - values = values2; - } - - public void clear() { - Arrays.fill(keys, NO_VALUE); - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/TPrimitiveMain.java b/src/main/java/com/google/code/java/core/primitives/TPrimitiveMain.java deleted file mode 100644 index c004391..0000000 --- a/src/main/java/com/google/code/java/core/primitives/TPrimitiveMain.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import gnu.trove.TIntIntHashMap; - -public class TPrimitiveMain { - public static void main(String... args) throws InterruptedException { - TIntIntHashMap counters = new TIntIntHashMap(); - while (true) { - performTest(counters); - Thread.sleep(100); - } - } - - private static void performTest(TIntIntHashMap counters) { - counters.clear(); - long start = System.nanoTime(); - int runs = 1000 * 1000; - for (int i = 0; i < runs; i++) { - int x = i % 1000; - int y = i / 1000; - int times = x * y; - int count = counters.get(times); - if (count == 0) - counters.put(times, 1); - else - counters.put(times, count + 1); - } - long time = System.nanoTime() - start; - System.out.printf("Took %,d ns per loop%n", time / runs); - } -} diff --git a/src/main/java/com/google/code/java/core/primitives/WrapperMain.java b/src/main/java/com/google/code/java/core/primitives/WrapperMain.java deleted file mode 100644 index 278cf5c..0000000 --- a/src/main/java/com/google/code/java/core/primitives/WrapperMain.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.primitives; - -import java.io.FileNotFoundException; -import java.util.HashMap; -import java.util.Map; - -public class WrapperMain { - private static final long START = System.currentTimeMillis(); - - public static void main(String... args) throws InterruptedException, FileNotFoundException { - int runs = 1200; - Map counters = new HashMap(); - Report out = new Report(runs); - System.gc(); - for (int i = 0; i < runs; i++) { - performTest(out, counters); - Thread.sleep(100); - } - out.print("wrappers-report.csv"); - } - - private static void performTest(Report out, Map counters) { - counters.clear(); - long start = System.nanoTime(); - int runs = 300 * 300; - for (Integer i = 0; i < runs; i++) { - Integer x = i % 300; - Integer y = i / 300; - Integer times = x * y; - Integer count = counters.get(times); - if (count == null) - counters.put(times, 1); - else - counters.put(times, count + 1); - } - long time = System.nanoTime() - start; - out.usedMB[out.count] = (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1e6; - out.timeFromStart[out.count] = (System.currentTimeMillis() - START) / 1e3; - out.avgTime[out.count] = (double) time / runs; - out.count++; - } -} diff --git a/src/main/java/com/google/code/java/core/service/TimedEchoDownstream.java b/src/main/java/com/google/code/java/core/service/TimedEchoDownstream.java deleted file mode 100644 index 32ea31b..0000000 --- a/src/main/java/com/google/code/java/core/service/TimedEchoDownstream.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service; - -public interface TimedEchoDownstream { - public void onEcho(int sequenceNumber, long nanoTime); -} diff --git a/src/main/java/com/google/code/java/core/service/TimedEchoUpstream.java b/src/main/java/com/google/code/java/core/service/TimedEchoUpstream.java deleted file mode 100644 index 0522151..0000000 --- a/src/main/java/com/google/code/java/core/service/TimedEchoUpstream.java +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service; - -public interface TimedEchoUpstream { - public void echo(int sequenceNumber, long nanoTime); -} diff --git a/src/main/java/com/google/code/java/core/service/api/ByteBufferConsumer.java b/src/main/java/com/google/code/java/core/service/api/ByteBufferConsumer.java deleted file mode 100644 index 0899338..0000000 --- a/src/main/java/com/google/code/java/core/service/api/ByteBufferConsumer.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.api; - -import java.nio.ByteBuffer; - -public interface ByteBufferConsumer { - public ByteBuffer acquireByteBuffer(int capacity); - - public void releaseByteBuffer(ByteBuffer bb); -} diff --git a/src/main/java/com/google/code/java/core/service/api/ByteBufferListener.java b/src/main/java/com/google/code/java/core/service/api/ByteBufferListener.java deleted file mode 100644 index 8f8334a..0000000 --- a/src/main/java/com/google/code/java/core/service/api/ByteBufferListener.java +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.api; - -import java.nio.ByteBuffer; - -public interface ByteBufferListener { - public void process(ByteBuffer bb); - - public void processOther(); -} diff --git a/src/main/java/com/google/code/java/core/service/api/Stoppable.java b/src/main/java/com/google/code/java/core/service/api/Stoppable.java deleted file mode 100644 index 489363f..0000000 --- a/src/main/java/com/google/code/java/core/service/api/Stoppable.java +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.api; - -public interface Stoppable { - public void stop(); - - public boolean isStopped(); -} diff --git a/src/main/java/com/google/code/java/core/service/async/AsyncConsumer.java b/src/main/java/com/google/code/java/core/service/async/AsyncConsumer.java deleted file mode 100644 index e86c656..0000000 --- a/src/main/java/com/google/code/java/core/service/async/AsyncConsumer.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.async; - -import com.google.code.java.core.service.api.ByteBufferConsumer; -import com.google.code.java.core.service.api.ByteBufferListener; -import com.google.code.java.core.service.api.Stoppable; -import com.google.code.java.core.service.concurrency.NamedThreadFactory; -import com.google.code.java.core.service.concurrency.PaddedAtomicReference; - -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicReference; - -public class AsyncConsumer implements Stoppable, ByteBufferConsumer { - private final int bufferSize; - private final ByteBufferListener listener; - - private final ExecutorService service; - private final AtomicReference bufferRef; - - private volatile boolean stopped = false; - - public AsyncConsumer(String name, int bufferSize, ByteBufferListener listener) { - service = Executors.newSingleThreadExecutor(new NamedThreadFactory(name, true)); - this.bufferSize = bufferSize; - this.listener = listener; - bufferRef = new PaddedAtomicReference(createBuffer()); - service.execute(new Consumer()); - } - - public ByteBuffer acquireByteBuffer(int capacity) { - while (!stopped) { - ByteBuffer bb = bufferRef.getAndSet(null); - if (bb.remaining() >= capacity) { - return bb; - } - // put the buffer back. - while (!bufferRef.compareAndSet(null, bb)) ; - } - throw new IllegalStateException("Stopped"); - } - - public void releaseByteBuffer(ByteBuffer bb) { - while (!bufferRef.compareAndSet(null, bb)) ; - } - - public ByteBuffer createBuffer() { - return ByteBuffer.allocateDirect(bufferSize).order(ByteOrder.nativeOrder()); - } - - @Override - public boolean isStopped() { - return stopped; - } - - public void stop() { - stopped = true; - service.shutdown(); - } - - class Consumer implements Runnable { - ByteBuffer bb = createBuffer(); - - @Override - public void run() { - try { - while (!stopped) { - run0(); - } - } catch (Throwable t) { - t.printStackTrace(); - } finally { - if (!stopped) - System.err.println("Consumer dying."); - } - } - - private void run0() { - do { - bb = bufferRef.getAndSet(bb); - } while (bb == null); - if (bb.position() == 0) { - listener.processOther(); - } else { - bb.flip(); - listener.process(bb); - bb.clear(); - } - } - } -} diff --git a/src/main/java/com/google/code/java/core/service/async/AsyncSocketClient.java b/src/main/java/com/google/code/java/core/service/async/AsyncSocketClient.java deleted file mode 100644 index c5fbd51..0000000 --- a/src/main/java/com/google/code/java/core/service/async/AsyncSocketClient.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.async; - -import com.google.code.java.core.service.api.ByteBufferListener; -import com.google.code.java.core.service.api.Stoppable; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; - -public class AsyncSocketClient implements Stoppable { - private final String hostname; - private final int port; - private final AsyncConsumer consumer; - private final ByteBufferListener downStreamListener; - private final ByteBuffer readingBuffer; - - public AsyncSocketClient(String hostname, int port, int bufferSize, ByteBufferListener downStreamListener) { - this.hostname = hostname; - this.port = port; - this.consumer = new AsyncConsumer(hostname + ':' + port + "-client", bufferSize, new MyByteBufferListener()); - this.downStreamListener = downStreamListener; - readingBuffer = consumer.createBuffer(); - } - - @Override - public boolean isStopped() { - return consumer.isStopped(); - } - - @Override - public void stop() { - consumer.stop(); - } - - class MyByteBufferListener implements ByteBufferListener { - // owned by the async thread. - private SocketChannel socketChannel = null; - - // called by the async thread. - @Override - public void process(ByteBuffer bb) { - ensureConnected(); - - try { - while (bb.remaining() > 0) - socketChannel.write(bb); - - } catch (IOException e) { - if (!isStopped()) - e.printStackTrace(); - closeSocketChannel(); - } - } - - // called by the async thread. - @Override - public void processOther() { - if (socketChannel == null) return; - try { - int len = socketChannel.read(readingBuffer); - if (len < 0) { - closeSocketChannel(); - return; - } else if (len == 0) { - downStreamListener.processOther(); - return; - } - readingBuffer.flip(); - downStreamListener.process(readingBuffer); - readingBuffer.compact(); - - } catch (IOException e) { - if (!isStopped()) - e.printStackTrace(); - } - } - - private void ensureConnected() { - if (socketChannel != null) - return; - while (!isStopped()) { - try { - socketChannel = SocketChannel.open(new InetSocketAddress(hostname, port)); - socketChannel.configureBlocking(false); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - } - - private void closeSocketChannel() { - if (socketChannel != null) { - try { - socketChannel.close(); - } catch (IOException ignored) { - } - } - socketChannel = null; - } - - } -} diff --git a/src/main/java/com/google/code/java/core/service/concurrency/NamedThreadFactory.java b/src/main/java/com/google/code/java/core/service/concurrency/NamedThreadFactory.java deleted file mode 100644 index 302f1db..0000000 --- a/src/main/java/com/google/code/java/core/service/concurrency/NamedThreadFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.concurrency; - -import java.util.concurrent.ThreadFactory; - -public class NamedThreadFactory implements ThreadFactory { - private final String name; - private final boolean daemon; - - public NamedThreadFactory(String name, boolean daemon) { - this.name = name; - this.daemon = daemon; - } - - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(r, name); - t.setDaemon(daemon); - return t; - } -} diff --git a/src/main/java/com/google/code/java/core/service/concurrency/PaddedAtomicReference.java b/src/main/java/com/google/code/java/core/service/concurrency/PaddedAtomicReference.java deleted file mode 100644 index f397210..0000000 --- a/src/main/java/com/google/code/java/core/service/concurrency/PaddedAtomicReference.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.concurrency; - -import java.util.concurrent.atomic.AtomicReference; - -public class PaddedAtomicReference extends AtomicReference { - public long p2, p3, p4, p5, p6, p7; - - public PaddedAtomicReference(T t) { - super(t); - } - - public long sumPadded() { - return p2 + p3 + p4 + p5 + p6 + p7; - } -} diff --git a/src/main/java/com/google/code/java/core/sizeof/SizeofUtil.java b/src/main/java/com/google/code/java/core/sizeof/SizeofUtil.java deleted file mode 100644 index 0a28cc5..0000000 --- a/src/main/java/com/google/code/java/core/sizeof/SizeofUtil.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.sizeof; - -import java.util.Arrays; - -public abstract class SizeofUtil { - public double averageBytes() { - int runs = runs(); - double[] sizes = new double[runs]; - int retries = runs / 2; - final Runtime runtime = Runtime.getRuntime(); - for (int i = 0; i < runs; i++) { - Thread.yield(); - long used1 = memoryUsed(runtime); - int number = create(); - long used2 = memoryUsed(runtime); - double avgSize = (double) (used2 - used1) / number; -// System.out.println(avgSize); - if (avgSize < 0) { - // GC was performed. - i--; - if (retries-- < 0) - throw new RuntimeException("The eden space is not large enough to hold all the objects."); - } else if (avgSize == 0) { - throw new RuntimeException("Object is not large enough to register, try turning off the TLAB with -XX:-UseTLAB"); - } else { - sizes[i] = avgSize; - } - } - Arrays.sort(sizes); - return sizes[runs / 2]; - } - - protected long memoryUsed(Runtime runtime) { - return runtime.totalMemory() - runtime.freeMemory(); - } - - protected int runs() { - return 11; - } - - protected abstract int create(); -} diff --git a/src/main/java/com/google/code/java/core/socket/EchoService.java b/src/main/java/com/google/code/java/core/socket/EchoService.java deleted file mode 100644 index 88c9e5a..0000000 --- a/src/main/java/com/google/code/java/core/socket/EchoService.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.socket; - -import com.google.code.java.core.service.concurrency.NamedThreadFactory; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public class EchoService { - private final ExecutorService service = Executors.newCachedThreadPool(new NamedThreadFactory("echo", true)); - private final ServerSocketChannel ssc; - - public EchoService(int port) throws IOException, InterruptedException { - ssc = ServerSocketChannel.open(); - ssc.socket().setReuseAddress(true); - try { - ssc.socket().bind(new InetSocketAddress(port)); - } catch (IOException e) { - Thread.sleep(100); - ssc.socket().bind(new InetSocketAddress(port)); - } - service.execute(new Acceptor()); - } - - public static void main(String[] args) throws IOException, InterruptedException { - int port = args.length > 0 ? Integer.parseInt(args[0]) : 12345; - System.out.println("Listening on port " + port); - EchoService es = new EchoService(port); - System.in.read(); - } - - public void stop() { - service.shutdown(); - try { - ssc.close(); - } catch (IOException ignored) { - } - } - - class Acceptor implements Runnable { - @Override - public void run() { - try { - while (!Thread.interrupted()) { - SocketChannel sc = ssc.accept(); - service.execute(new EchoHandler(sc)); - } - } catch (Exception e) { - if (!service.isShutdown()) - e.printStackTrace(); - } finally { - try { - ssc.close(); - } catch (IOException ignored) { - } - } - } - } - - static class EchoHandler implements Runnable { - private final SocketChannel sc; - - public EchoHandler(SocketChannel sc) { - this.sc = sc; - } - - @Override - public void run() { - try { - ByteBuffer bb = ByteBuffer.allocateDirect(256 * 1024); - while (sc.isOpen()) { - if (sc.read(bb) < 0) - break; - bb.flip(); - sc.write(bb); - bb.flip(); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - sc.close(); - } catch (IOException ignored) { - } - } - } - } -} diff --git a/src/main/java/com/google/code/java/core/time/BusyHiresTimer.java b/src/main/java/com/google/code/java/core/time/BusyHiresTimer.java deleted file mode 100644 index 197c06a..0000000 --- a/src/main/java/com/google/code/java/core/time/BusyHiresTimer.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.google.code.java.core.time; - -/** - * @author peter.lawrey - */ -public enum BusyHiresTimer { - ; - private static volatile long counter; - private static int factor; - - static { - Thread t = new Thread(new Runnable() { - public void run() { - while (!Thread.interrupted()) - counter++; - } - }); - t.setDaemon(true); - t.start(); - } - - public static long nanoTime() { - if (factor == 0) { - init(); - init(); - } - return (counter * factor) >> 8; - } - - private static void init() { - while (counter < 1) - Thread.yield(); - long start0 = System.nanoTime(); - long start; - while ((start = System.nanoTime()) == start0) ; - long counter1 = counter; - if (counter1 == 0) throw new IllegalStateException("thread not started."); - long end0 = start + 50 * 1000 * 1000; // 50 ms - long end; - while ((end = System.nanoTime()) < end0) ; - long counter2 = counter; - factor = (int) (((end - start) << 8) / (counter2 - counter1)); - System.out.printf("Each count takes %.2f ns%n", factor / 256.0); - } -} diff --git a/src/main/java/com/google/code/java/core/time/HiresTimer.java b/src/main/java/com/google/code/java/core/time/HiresTimer.java deleted file mode 100644 index 510e8be..0000000 --- a/src/main/java/com/google/code/java/core/time/HiresTimer.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.google.code.java.core.time;/* - Copyright 2011 Peter Lawrey - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import java.text.DecimalFormat; -import java.text.SimpleDateFormat; -import java.util.TimeZone; - -public enum HiresTimer { - ; - private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss.SSS"); - private static final DecimalFormat DF = new DecimalFormat("000"); - private static long s_deltaUS; - - static { - SDF.setTimeZone(TimeZone.getTimeZone("GMT")); - long now, nowNs, now0 = System.currentTimeMillis(); - // wait for the milli-seconds to change. - do { - nowNs = System.nanoTime(); - } while ((now = System.currentTimeMillis()) == now0); - s_deltaUS = now * 1000 - (nowNs + 500) / 1000; - } - - public static long currentTimeUS() { - long now = System.currentTimeMillis() * 1000; - long nowUS = (System.nanoTime() + 500) / 1000 + s_deltaUS; - if (nowUS < now) { - s_deltaUS++; - return now; - } else if (nowUS > now + 999) { - s_deltaUS--; - return now; - } - return nowUS; - } - - public static String toString(long timeUS) { - return SDF.format(timeUS / 1000) + DF.format(timeUS % 1000); - } -} diff --git a/src/main/java/knucleotide.java b/src/main/java/knucleotide.java deleted file mode 100644 index b64fd0c..0000000 --- a/src/main/java/knucleotide.java +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -/* The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - - contributed by Peter Lawrey -*/ - -import java.io.FileInputStream; -import java.lang.management.ManagementFactory; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.FileChannel; -import java.util.*; -import java.util.concurrent.*; - -public class knucleotide { - static final String ATCG = "ATCG"; - static final int A = 0, T = 1, C = 2, G = 3; - static final int LONGEST_SEARCH = 18; - public static final int WARMUP = LONGEST_SEARCH + 2; - static final long MASK18 = (1L << (2 * LONGEST_SEARCH)) - 1; - - static byte[] values = new byte[256]; static { - Arrays.fill(values, (byte) -1); - values['A'] = values['a'] = A; - values['T'] = values['t'] = T; - values['C'] = values['c'] = C; - values['G'] = values['g'] = G; - } - - private static long encode(String code) { - long l = 0; - for (int i = 0; i < code.length(); i++) - l = (l << 2) | values[code.charAt(i)]; - return l; - } - - static final long GGT = encode("GGT"); - static final long GGTA = encode("GGTA"); - static final long GGTATT = encode("GGTATT"); - static final long GGTATTTTAATT = encode("GGTATTTTAATT"); - static final long GGTATTTTAATTTATAGT = encode("GGTATTTTAATTTATAGT"); - - static int nThreads = Runtime.getRuntime().availableProcessors(); - - public static void main(String... args) throws Exception { - String processId = ManagementFactory.getRuntimeMXBean().getName().split("@")[0]; - FileInputStream in = new FileInputStream("/proc/" + processId + "/fd/0"); - ExecutorService es = Executors.newFixedThreadPool(nThreads - 1); - FileChannel fc = in.getChannel(); - ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); - int startFrom = findStartOfThree(bb, es, nThreads); - bb.position(startFrom); - - int blockSize = (bb.remaining() + nThreads - 1) / nThreads; - for (int i = 0; i < nThreads; i++) { - int min = startFrom + i * blockSize; - int max = min + blockSize; - bb.limit(Math.min(max, bb.capacity())); - bb.position(min - WARMUP); - final ByteBuffer bb3 = bb.slice().order(ByteOrder.nativeOrder()); - final boolean warmup = i > 0; - final Runnable task = new Runnable() { - @Override - public void run() { - new Results().process(bb3, 0, bb3.limit(), warmup); - } - }; - if (i < nThreads - 1) - es.submit(task); - else - task.run(); - } - - in.close(); - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - Results.report((char) bb.get(startFrom)); - } - - private static int findStartOfThree(ByteBuffer bb, ExecutorService es, int nThreads) throws InterruptedException { - final ArrayBlockingQueue startOfThree = new ArrayBlockingQueue(1); - int blockSize = bb.remaining() / nThreads; - for (int i = 0; i < nThreads; i++) { - final int min = i * blockSize; - final int max = min + blockSize; - final FindThreeRunnable task = new FindThreeRunnable(bb, startOfThree, min, max); - if (i == nThreads - 1) - task.run(); - else - es.submit(task); - } - return startOfThree.take(); - } - - static class Results { - static final int LEN = 256 * 1024; - static final int KEY_SIZE = 2 * LONGEST_SEARCH; - static final long COUNT_BASE = 1L << KEY_SIZE; - static final long KEY_MASK = COUNT_BASE - 1; - final long[] keyValues = new long[LEN]; - static final Set ALL_RESULTS = new CopyOnWriteArraySet(); - - Results() { - ALL_RESULTS.add(this); - } - - void increment(long id) { - if (!tryIncrement(id, id)) return; - for (int i = 1; i < LEN; i++) - if (!tryIncrement(id, id + i)) return; - throw new AssertionError(id); - } - - private boolean tryIncrement(long id, long id2) { - int hash = (int) ((id2 + (id2 >>> 17)) & (LEN - 1)); - long key = keyValues[hash]; - if (key == 0) { - keyValues[hash] = id | COUNT_BASE; - } else if ((key & KEY_MASK) == id) { - keyValues[hash] += COUNT_BASE; - } else { - return true; - } - return false; - } - - public static void report(char firstLetter) { - int[] count1s = new int[4]; - int[] count2s = new int[4 * 4]; - int[] ggtCounts = new int[5]; - for (Results results : ALL_RESULTS) - for (long key1 : results.keyValues) { - if (key1 == 0) continue; - final long key = key1 & KEY_MASK; - final int value = (int) (key1 >>> KEY_SIZE); - - count1s[((int) (key & ((1 << 2 * 1) - 1)))] += value; - count2s[((int) (key & ((1 << 2 * 2) - 1)))] += value; - if ((key & ((1 << 2 * 3) - 1)) == GGT) ggtCounts[0] += value; - if ((key & ((1 << 2 * 4) - 1)) == GGTA) ggtCounts[1] += value; - if ((key & ((1 << 2 * 6) - 1)) == GGTATT) ggtCounts[2] += value; - if ((key & ((1 << 2 * 12) - 1)) == GGTATTTTAATT) ggtCounts[3] += value; - if (key == GGTATTTTAATTTATAGT) ggtCounts[4] += value; - } - // first letter is counted incorrectly as a pair when there was no previous letter. - count2s[((int) encode("A" + firstLetter))]--; - long sum = 0; - SortedMap singles = new TreeMap(Collections.reverseOrder()); - for (int i = 0, count1sLength = count1s.length; i < count1sLength; i++) { - sum += count1s[i]; - singles.put(count1s[i], i); - } - for (Map.Entry entry : singles.entrySet()) - System.out.printf("" + ATCG.charAt(entry.getValue()) + " %5.3f%n", 100.0 * entry.getKey() / sum); - System.out.println(); - SortedMap pairs = new TreeMap(Collections.reverseOrder()); - for (int i = 0, count2sLength = count2s.length; i < count2sLength; i++) - pairs.put(count2s[i], i); - for (Map.Entry entry : pairs.entrySet()) - System.out.printf("" + ATCG.charAt(entry.getValue() / 4) + ATCG.charAt(entry.getValue() % 4) + " %5.3f%n", 100.0 * entry.getKey() / sum); - System.out.println(); - String[] names = "GGT GGTA GGTATT GGTATTTTAATT GGTATTTTAATTTATAGT".split(" "); - for (int i = 0; i < ggtCounts.length; i++) - System.out.printf("%d\t%s%n", ggtCounts[i], names[i]); - } - - public void process(ByteBuffer bytes, int start, int end, boolean warmup) { - long l = 0; - if (warmup) - for (int i = start; i < start + WARMUP; i++) { - int b = values[bytes.get(i)]; - if (b < 0) continue; - l = (l << 2) | b; - } - - for (int i = start + WARMUP; i < end; i++) { - int b = values[bytes.get(i)]; - if (b < 0) continue; - l = (l << 2) | b; - increment(l & MASK18); - } - } - } - - static class FindThreeRunnable implements Runnable { - static final int THREE_L = ('>' << 24) | ('T' << 16) | ('H' << 8) | ('R' << 0); - static final int THREE_B = ('>' << 0) | ('T' << 8) | ('H' << 16) | ('R' << 24); - - static volatile boolean found = false; - private final ByteBuffer bb; - private final BlockingQueue startOfThree; - private final int min; - private final int max; - - public FindThreeRunnable(ByteBuffer bb, BlockingQueue startOfThree, int min, int max) { - this.bb = bb; - this.startOfThree = startOfThree; - this.min = min; - this.max = max; - } - - @Override - public void run() { - try { - for (int i = min; i < max && !found; i++) { - switch (bb.getInt(i)) { - case THREE_B: - case THREE_L: - while (bb.get(i++) != '\n') ; - startOfThree.add(i); - found = true; - return; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/test/cpp/MemoryAlignment/.dep.inc b/src/test/cpp/MemoryAlignment/.dep.inc deleted file mode 100644 index 4560e55..0000000 --- a/src/test/cpp/MemoryAlignment/.dep.inc +++ /dev/null @@ -1,5 +0,0 @@ -# This code depends on make tool being used -DEPFILES=$(wildcard $(addsuffix .d, ${OBJECTFILES})) -ifneq (${DEPFILES},) -include ${DEPFILES} -endif diff --git a/src/test/cpp/MemoryAlignment/Makefile b/src/test/cpp/MemoryAlignment/Makefile deleted file mode 100644 index ec9de69..0000000 --- a/src/test/cpp/MemoryAlignment/Makefile +++ /dev/null @@ -1,128 +0,0 @@ -# -# There exist several targets which are by default empty and which can be -# used for execution of your targets. These targets are usually executed -# before and after some main targets. They are: -# -# .build-pre: called before 'build' target -# .build-post: called after 'build' target -# .clean-pre: called before 'clean' target -# .clean-post: called after 'clean' target -# .clobber-pre: called before 'clobber' target -# .clobber-post: called after 'clobber' target -# .all-pre: called before 'all' target -# .all-post: called after 'all' target -# .help-pre: called before 'help' target -# .help-post: called after 'help' target -# -# Targets beginning with '.' are not intended to be called on their own. -# -# Main targets can be executed directly, and they are: -# -# build build a specific configuration -# clean remove built files from a configuration -# clobber remove all built files -# all build all configurations -# help print help mesage -# -# Targets .build-impl, .clean-impl, .clobber-impl, .all-impl, and -# .help-impl are implemented in nbproject/makefile-impl.mk. -# -# Available make variables: -# -# CND_BASEDIR base directory for relative paths -# CND_DISTDIR default top distribution directory (build artifacts) -# CND_BUILDDIR default top build directory (object files, ...) -# CONF name of current configuration -# CND_PLATFORM_${CONF} platform name (current configuration) -# CND_ARTIFACT_DIR_${CONF} directory of build artifact (current configuration) -# CND_ARTIFACT_NAME_${CONF} name of build artifact (current configuration) -# CND_ARTIFACT_PATH_${CONF} path to build artifact (current configuration) -# CND_PACKAGE_DIR_${CONF} directory of package (current configuration) -# CND_PACKAGE_NAME_${CONF} name of package (current configuration) -# CND_PACKAGE_PATH_${CONF} path to package (current configuration) -# -# NOCDDL - - -# Environment -MKDIR=mkdir -CP=cp -CCADMIN=CCadmin - - -# build -build: .build-post - -.build-pre: -# Add your pre 'build' code here... - -.build-post: .build-impl -# Add your post 'build' code here... - - -# clean -clean: .clean-post - -.clean-pre: -# Add your pre 'clean' code here... - -.clean-post: .clean-impl -# Add your post 'clean' code here... - - -# clobber -clobber: .clobber-post - -.clobber-pre: -# Add your pre 'clobber' code here... - -.clobber-post: .clobber-impl -# Add your post 'clobber' code here... - - -# all -all: .all-post - -.all-pre: -# Add your pre 'all' code here... - -.all-post: .all-impl -# Add your post 'all' code here... - - -# build tests -build-tests: .build-tests-post - -.build-tests-pre: -# Add your pre 'build-tests' code here... - -.build-tests-post: .build-tests-impl -# Add your post 'build-tests' code here... - - -# run tests -test: .test-post - -.test-pre: -# Add your pre 'test' code here... - -.test-post: .test-impl -# Add your post 'test' code here... - - -# help -help: .help-post - -.help-pre: -# Add your pre 'help' code here... - -.help-post: .help-impl -# Add your post 'help' code here... - - - -# include project implementation makefile -include nbproject/Makefile-impl.mk - -# include project make variables -include nbproject/Makefile-variables.mk diff --git a/src/test/cpp/MemoryAlignment/main.cpp b/src/test/cpp/MemoryAlignment/main.cpp deleted file mode 100644 index c89e054..0000000 --- a/src/test/cpp/MemoryAlignment/main.cpp +++ /dev/null @@ -1,147 +0,0 @@ -/* - * File: main.cpp - * Author: peter - * - * Created on 10 September 2011, 08:48 - */ - -#include -#include -#include - -using namespace std; - -class OneInt { - int i; -}; - -class TwoInt { - int i, j; -}; - -class ThreeInt { - int i, j, k; -}; - -class FourInt { - int i, j, k, l; -}; - -class FiveInt { - int i, j, k, l, m; -}; - -class SixInt { - int i, j, k, l, m, n; -}; - -class SevenInt { - int i, j, k, l, m, n, o; -}; - -class EightInt { - int i, j, k, l, m, n, o, p; -}; - -class OnePtr { - void * i; -}; - -class TwoPtr { - void * i, *j; -}; - -class ThreePtr { - void * i, *j, *k; -}; - -class FourPtr { - void * i, *j, *k, *l; -}; - -class FivePtr { - void * i, *j, *k, *l, *m; -}; - -class SixPtr { - void * i, *j, *k, *l, *m, *n; -}; - -class SevenPtr { - void * i, *j, *k, *l, *m, *n, *o; -}; - -class EightPtr { - void * i, *j, *k, *l, *m, *n, *o, *p; -}; - -/* - * - */ -int main(int argc, char** argv) { - for (int i = 0; i <= 64; i++) { - char *p = (char *) malloc(i); - char *q = (char *) malloc(i); - size_t reserved = q - p; - cout << "malloc(" << i << ") reserved " << reserved << " bytes" << endl; - } - { - // int values. - cout << "heap class with one int reserved " << -((char *) new OneInt() - (char *) new OneInt()) << " bytes" << endl; - OneInt p1, q1; - cout << "stack class with one int reserved " << abs((char *) &q1 - (char *) &p1) << " bytes" << endl; - cout << "heap class with one int reserved " << -((char *) new OneInt() - (char *) new OneInt()) << " bytes" << endl; - OneInt p1b, q1b; - cout << "stack class with one int reserved " << abs((char *) &q1b - (char *) &p1b) << " bytes" << endl; - cout << "heap class with two int reserved " << -((char *) new TwoInt() - (char *) new TwoInt()) << " bytes" << endl; - TwoInt p2, q2; - cout << "stack class with two int reserved " << abs((char *) &q2 - (char *) &p2) << " bytes" << endl; - cout << "heap class with three int reserved " << -((char *) new ThreeInt() - (char *) new ThreeInt()) << " bytes" << endl; - ThreeInt p3, q3; - cout << "stack class with three int reserved " << abs((char *) &q3 - (char *) &p3) << " bytes" << endl; - cout << "heap class with four int reserved " << -((char *) new FourInt() - (char *) new FourInt()) << " bytes" << endl; - FourInt p4, q4; - cout << "stack class with four int reserved " << abs((char *) &q4 - (char *) &p4) << " bytes" << endl; - cout << "heap class with five int reserved " << -((char *) new FiveInt() - (char *) new FiveInt()) << " bytes" << endl; - FiveInt p5, q5; - cout << "stack class with five int reserved " << abs((char *) &q5 - (char *) &p5) << " bytes" << endl; - cout << "heap class with six int reserved " << -((char *) new SixInt() - (char *) new SixInt()) << " bytes" << endl; - SixInt p6, q6; - cout << "stack class with six int reserved " << abs((char *) &q6 - (char *) &p6) << " bytes" << endl; - cout << "heap class with seven int reserved " << -((char *) new SevenInt() - (char *) new SevenInt()) << " bytes" << endl; - SevenInt p7, q7; - cout << "stack class with seven int reserved " << abs((char *) &q7 - (char *) &p7) << " bytes" << endl; - cout << "heap class with eight int reserved " << -((char *) new EightInt() - (char *) new EightInt()) << " bytes" << endl; - EightInt p8, q8; - cout << "stack class with eight int reserved " << abs((char *) &q8 - (char *) &p8) << " bytes" << endl; - } - { - // pointers values. - cout << "heap class with one pointer reserved " << -((char *) new OnePtr() - (char *) new OnePtr()) << " bytes" << endl; - OnePtr p1, q1; - cout << "stack class with one pointer reserved " << abs((char *) &q1 - (char *) &p1) << " bytes" << endl; - cout << "heap class with two pointer reserved " << -((char *) new TwoPtr() - (char *) new TwoPtr()) << " bytes" << endl; - TwoPtr p2, q2; - cout << "stack class with two pointer reserved " << abs((char *) &q2 - (char *) &p2) << " bytes" << endl; - cout << "heap class with three pointer reserved " << -((char *) new ThreePtr() - (char *) new ThreePtr()) << " bytes" << endl; - ThreePtr p3, q3; - cout << "stack class with three pointer reserved " << abs((char *) &q3 - (char *) &p3) << " bytes" << endl; - cout << "heap class with four pointer reserved " << -((char *) new FourPtr() - (char *) new FourPtr()) << " bytes" << endl; - FourPtr p4, q4; - cout << "stack class with four pointer reserved " << abs((char *) &q4 - (char *) &p4) << " bytes" << endl; - cout << "heap class with five pointer reserved " << -((char *) new FivePtr() - (char *) new FivePtr()) << " bytes" << endl; - FivePtr p5, q5; - cout << "stack class with five pointer reserved " << abs((char *) &q5 - (char *) &p5) << " bytes" << endl; - cout << "heap class with six pointer reserved " << -((char *) new SixPtr() - (char *) new SixPtr()) << " bytes" << endl; - SixPtr p6, q6; - cout << "stack class with six pointer reserved " << abs((char *) &q6 - (char *) &p6) << " bytes" << endl; - cout << "heap class with seven pointer reserved " << -((char *) new SevenPtr() - (char *) new SevenPtr()) << " bytes" << endl; - SevenPtr p7, q7; - cout << "stack class with seven pointer reserved " << abs((char *) &q7 - (char *) &p7) << " bytes" << endl; - cout << "heap class with eight pointer reserved " << -((char *) new EightPtr() - (char *) new EightPtr()) << " bytes" << endl; - EightPtr p8, q8; - cout << "stack class with eight pointer reserved " << abs((char *) &q8 - (char *) &p8) << " bytes" << endl; - } - return 0; -} - diff --git a/src/test/cpp/MemoryAlignment/nbproject/Makefile-Debug.mk b/src/test/cpp/MemoryAlignment/nbproject/Makefile-Debug.mk deleted file mode 100644 index fac60a0..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/Makefile-Debug.mk +++ /dev/null @@ -1,83 +0,0 @@ -# -# Generated Makefile - do not edit! -# -# Edit the Makefile in the project folder instead (../Makefile). Each target -# has a -pre and a -post target defined where you can add customized code. -# -# This makefile implements configuration specific macros and targets. - - -# Environment -MKDIR=mkdir -CP=cp -GREP=grep -NM=nm -CCADMIN=CCadmin -RANLIB=ranlib -CC=gcc -CCC=g++ -CXX=g++ -FC=gfortran -AS=as - -# Macros -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Debug -CND_DISTDIR=dist -CND_BUILDDIR=build - -# Include project Makefile -include Makefile - -# Object Directory -OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM} - -# Object Files -OBJECTFILES= \ - ${OBJECTDIR}/main.o - - -# C Compiler Flags -CFLAGS= - -# CC Compiler Flags -CCFLAGS= -CXXFLAGS= - -# Fortran Compiler Flags -FFLAGS= - -# Assembler Flags -ASFLAGS= - -# Link Libraries and Options -LDLIBSOPTIONS= - -# Build Targets -.build-conf: ${BUILD_SUBPROJECTS} - "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment - -${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment: ${OBJECTFILES} - ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} - ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment ${OBJECTFILES} ${LDLIBSOPTIONS} - -${OBJECTDIR}/main.o: main.cpp - ${MKDIR} -p ${OBJECTDIR} - ${RM} $@.d - $(COMPILE.cc) -g -MMD -MP -MF $@.d -o ${OBJECTDIR}/main.o main.cpp - -# Subprojects -.build-subprojects: - -# Clean Targets -.clean-conf: ${CLEAN_SUBPROJECTS} - ${RM} -r ${CND_BUILDDIR}/${CND_CONF} - ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment - -# Subprojects -.clean-subprojects: - -# Enable dependency checking -.dep.inc: .depcheck-impl - -include .dep.inc diff --git a/src/test/cpp/MemoryAlignment/nbproject/Makefile-Release.mk b/src/test/cpp/MemoryAlignment/nbproject/Makefile-Release.mk deleted file mode 100644 index ea74fd1..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/Makefile-Release.mk +++ /dev/null @@ -1,83 +0,0 @@ -# -# Generated Makefile - do not edit! -# -# Edit the Makefile in the project folder instead (../Makefile). Each target -# has a -pre and a -post target defined where you can add customized code. -# -# This makefile implements configuration specific macros and targets. - - -# Environment -MKDIR=mkdir -CP=cp -GREP=grep -NM=nm -CCADMIN=CCadmin -RANLIB=ranlib -CC=gcc -CCC=g++ -CXX=g++ -FC=gfortran -AS=as - -# Macros -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Release -CND_DISTDIR=dist -CND_BUILDDIR=build - -# Include project Makefile -include Makefile - -# Object Directory -OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM} - -# Object Files -OBJECTFILES= \ - ${OBJECTDIR}/main.o - - -# C Compiler Flags -CFLAGS= - -# CC Compiler Flags -CCFLAGS= -CXXFLAGS= - -# Fortran Compiler Flags -FFLAGS= - -# Assembler Flags -ASFLAGS= - -# Link Libraries and Options -LDLIBSOPTIONS= - -# Build Targets -.build-conf: ${BUILD_SUBPROJECTS} - "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment - -${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment: ${OBJECTFILES} - ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} - ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment ${OBJECTFILES} ${LDLIBSOPTIONS} - -${OBJECTDIR}/main.o: main.cpp - ${MKDIR} -p ${OBJECTDIR} - ${RM} $@.d - $(COMPILE.cc) -O2 -MMD -MP -MF $@.d -o ${OBJECTDIR}/main.o main.cpp - -# Subprojects -.build-subprojects: - -# Clean Targets -.clean-conf: ${CLEAN_SUBPROJECTS} - ${RM} -r ${CND_BUILDDIR}/${CND_CONF} - ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment - -# Subprojects -.clean-subprojects: - -# Enable dependency checking -.dep.inc: .depcheck-impl - -include .dep.inc diff --git a/src/test/cpp/MemoryAlignment/nbproject/Makefile-impl.mk b/src/test/cpp/MemoryAlignment/nbproject/Makefile-impl.mk deleted file mode 100644 index 09ff893..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/Makefile-impl.mk +++ /dev/null @@ -1,133 +0,0 @@ -# -# Generated Makefile - do not edit! -# -# Edit the Makefile in the project folder instead (../Makefile). Each target -# has a pre- and a post- target defined where you can add customization code. -# -# This makefile implements macros and targets common to all configurations. -# -# NOCDDL - - -# Building and Cleaning subprojects are done by default, but can be controlled with the SUB -# macro. If SUB=no, subprojects will not be built or cleaned. The following macro -# statements set BUILD_SUB-CONF and CLEAN_SUB-CONF to .build-reqprojects-conf -# and .clean-reqprojects-conf unless SUB has the value 'no' -SUB_no=NO -SUBPROJECTS=${SUB_${SUB}} -BUILD_SUBPROJECTS_=.build-subprojects -BUILD_SUBPROJECTS_NO= -BUILD_SUBPROJECTS=${BUILD_SUBPROJECTS_${SUBPROJECTS}} -CLEAN_SUBPROJECTS_=.clean-subprojects -CLEAN_SUBPROJECTS_NO= -CLEAN_SUBPROJECTS=${CLEAN_SUBPROJECTS_${SUBPROJECTS}} - - -# Project Name -PROJECTNAME=MemoryAlignment - -# Active Configuration -DEFAULTCONF=Debug -CONF=${DEFAULTCONF} - -# All Configurations -ALLCONFS=Debug Release - - -# build -.build-impl: .build-pre .validate-impl .depcheck-impl - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .build-conf - - -# clean -.clean-impl: .clean-pre .validate-impl .depcheck-impl - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .clean-conf - - -# clobber -.clobber-impl: .clobber-pre .depcheck-impl - @#echo "=> Running $@..." - for CONF in ${ALLCONFS}; \ - do \ - "${MAKE}" -f nbproject/Makefile-$${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .clean-conf; \ - done - -# all -.all-impl: .all-pre .depcheck-impl - @#echo "=> Running $@..." - for CONF in ${ALLCONFS}; \ - do \ - "${MAKE}" -f nbproject/Makefile-$${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .build-conf; \ - done - -# build tests -.build-tests-impl: .build-impl .build-tests-pre - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk SUBPROJECTS=${SUBPROJECTS} .build-tests-conf - -# run tests -.test-impl: .build-tests-impl .test-pre - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk SUBPROJECTS=${SUBPROJECTS} .test-conf - -# dependency checking support -.depcheck-impl: - @echo "# This code depends on make tool being used" >.dep.inc - @if [ -n "${MAKE_VERSION}" ]; then \ - echo "DEPFILES=\$$(wildcard \$$(addsuffix .d, \$${OBJECTFILES}))" >>.dep.inc; \ - echo "ifneq (\$${DEPFILES},)" >>.dep.inc; \ - echo "include \$${DEPFILES}" >>.dep.inc; \ - echo "endif" >>.dep.inc; \ - else \ - echo ".KEEP_STATE:" >>.dep.inc; \ - echo ".KEEP_STATE_FILE:.make.state.\$${CONF}" >>.dep.inc; \ - fi - -# configuration validation -.validate-impl: - @if [ ! -f nbproject/Makefile-${CONF}.mk ]; \ - then \ - echo ""; \ - echo "Error: can not find the makefile for configuration '${CONF}' in project ${PROJECTNAME}"; \ - echo "See 'make help' for details."; \ - echo "Current directory: " `pwd`; \ - echo ""; \ - fi - @if [ ! -f nbproject/Makefile-${CONF}.mk ]; \ - then \ - exit 1; \ - fi - - -# help -.help-impl: .help-pre - @echo "This makefile supports the following configurations:" - @echo " ${ALLCONFS}" - @echo "" - @echo "and the following targets:" - @echo " build (default target)" - @echo " clean" - @echo " clobber" - @echo " all" - @echo " help" - @echo "" - @echo "Makefile Usage:" - @echo " make [CONF=] [SUB=no] build" - @echo " make [CONF=] [SUB=no] clean" - @echo " make [SUB=no] clobber" - @echo " make [SUB=no] all" - @echo " make help" - @echo "" - @echo "Target 'build' will build a specific configuration and, unless 'SUB=no'," - @echo " also build subprojects." - @echo "Target 'clean' will clean a specific configuration and, unless 'SUB=no'," - @echo " also clean subprojects." - @echo "Target 'clobber' will remove all built files from all configurations and," - @echo " unless 'SUB=no', also from subprojects." - @echo "Target 'all' will will build all configurations and, unless 'SUB=no'," - @echo " also build subprojects." - @echo "Target 'help' prints this message." - @echo "" - diff --git a/src/test/cpp/MemoryAlignment/nbproject/Makefile-variables.mk b/src/test/cpp/MemoryAlignment/nbproject/Makefile-variables.mk deleted file mode 100644 index ac7a00e..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/Makefile-variables.mk +++ /dev/null @@ -1,35 +0,0 @@ -# -# Generated - do not edit! -# -# NOCDDL -# -CND_BASEDIR=`pwd` -CND_BUILDDIR=build -CND_DISTDIR=dist -# Debug configuration -CND_PLATFORM_Debug=GNU-Linux-x86 -CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux-x86 -CND_ARTIFACT_NAME_Debug=memoryalignment -CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux-x86/memoryalignment -CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux-x86/package -CND_PACKAGE_NAME_Debug=memoryalignment.tar -CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux-x86/package/memoryalignment.tar -# Release configuration -CND_PLATFORM_Release=GNU-Linux-x86 -CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux-x86 -CND_ARTIFACT_NAME_Release=memoryalignment -CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux-x86/memoryalignment -CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux-x86/package -CND_PACKAGE_NAME_Release=memoryalignment.tar -CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux-x86/package/memoryalignment.tar -# -# include compiler specific variables -# -# dmake command -ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \ - (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk) -# -# gmake command -.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)) -# -include nbproject/private/Makefile-variables.mk diff --git a/src/test/cpp/MemoryAlignment/nbproject/Package-Debug.bash b/src/test/cpp/MemoryAlignment/nbproject/Package-Debug.bash deleted file mode 100644 index ac9a4ab..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/Package-Debug.bash +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -x - -# -# Generated - do not edit! -# - -# Macros -TOP=`pwd` -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Debug -CND_DISTDIR=dist -CND_BUILDDIR=build -NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging -TMPDIRNAME=tmp-packaging -OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment -OUTPUT_BASENAME=memoryalignment -PACKAGE_TOP_DIR=memoryalignment/ - -# Functions -function checkReturnCode -{ - rc=$? - if [ $rc != 0 ] - then - exit $rc - fi -} -function makeDirectory -# $1 directory path -# $2 permission (optional) -{ - mkdir -p "$1" - checkReturnCode - if [ "$2" != "" ] - then - chmod $2 "$1" - checkReturnCode - fi -} -function copyFileToTmpDir -# $1 from-file path -# $2 to-file path -# $3 permission -{ - cp "$1" "$2" - checkReturnCode - if [ "$3" != "" ] - then - chmod $3 "$2" - checkReturnCode - fi -} - -# Setup -cd "${TOP}" -mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package -rm -rf ${NBTMPDIR} -mkdir -p ${NBTMPDIR} - -# Copy files and create directories and links -cd "${TOP}" -makeDirectory "${NBTMPDIR}/memoryalignment/bin" -copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 - - -# Generate tar file -cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memoryalignment.tar -cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memoryalignment.tar * -checkReturnCode - -# Cleanup -cd "${TOP}" -rm -rf ${NBTMPDIR} diff --git a/src/test/cpp/MemoryAlignment/nbproject/Package-Release.bash b/src/test/cpp/MemoryAlignment/nbproject/Package-Release.bash deleted file mode 100644 index a2b3f96..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/Package-Release.bash +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -x - -# -# Generated - do not edit! -# - -# Macros -TOP=`pwd` -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Release -CND_DISTDIR=dist -CND_BUILDDIR=build -NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging -TMPDIRNAME=tmp-packaging -OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memoryalignment -OUTPUT_BASENAME=memoryalignment -PACKAGE_TOP_DIR=memoryalignment/ - -# Functions -function checkReturnCode -{ - rc=$? - if [ $rc != 0 ] - then - exit $rc - fi -} -function makeDirectory -# $1 directory path -# $2 permission (optional) -{ - mkdir -p "$1" - checkReturnCode - if [ "$2" != "" ] - then - chmod $2 "$1" - checkReturnCode - fi -} -function copyFileToTmpDir -# $1 from-file path -# $2 to-file path -# $3 permission -{ - cp "$1" "$2" - checkReturnCode - if [ "$3" != "" ] - then - chmod $3 "$2" - checkReturnCode - fi -} - -# Setup -cd "${TOP}" -mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package -rm -rf ${NBTMPDIR} -mkdir -p ${NBTMPDIR} - -# Copy files and create directories and links -cd "${TOP}" -makeDirectory "${NBTMPDIR}/memoryalignment/bin" -copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 - - -# Generate tar file -cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memoryalignment.tar -cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memoryalignment.tar * -checkReturnCode - -# Cleanup -cd "${TOP}" -rm -rf ${NBTMPDIR} diff --git a/src/test/cpp/MemoryAlignment/nbproject/configurations.xml b/src/test/cpp/MemoryAlignment/nbproject/configurations.xml deleted file mode 100644 index 6e9650d..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/configurations.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - main.cpp - - - - - Makefile - - - Makefile - - - - LOCAL_SOURCES - default - - - - - - - LOCAL_SOURCES - default - - - - 5 - - - 5 - - - 5 - - - 5 - - - - - diff --git a/src/test/cpp/MemoryAlignment/nbproject/private/Makefile-variables.mk b/src/test/cpp/MemoryAlignment/nbproject/private/Makefile-variables.mk deleted file mode 100644 index a64183e..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/private/Makefile-variables.mk +++ /dev/null @@ -1,7 +0,0 @@ -# -# Generated - do not edit! -# -# NOCDDL -# -# Debug configuration -# Release configuration diff --git a/src/test/cpp/MemoryAlignment/nbproject/private/configurations.xml b/src/test/cpp/MemoryAlignment/nbproject/private/configurations.xml deleted file mode 100644 index 39de30f..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/private/configurations.xml +++ /dev/null @@ -1,85 +0,0 @@ - - - - - Makefile - - - - localhost - 2 - - - - - - - - - - - - - - - - - gdb - - - - "${OUTPUT_PATH}" - - "${OUTPUT_PATH}" - - true - 0 - 0 - - - - - - - localhost - 2 - - - - - - - - - - - - - - - - - gdb - - - - "${OUTPUT_PATH}" - - "${OUTPUT_PATH}" - - true - 0 - 0 - - - - - - diff --git a/src/test/cpp/MemoryAlignment/nbproject/private/private.properties b/src/test/cpp/MemoryAlignment/nbproject/private/private.properties deleted file mode 100644 index bda28c6..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/private/private.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2011. Peter Lawrey -# -# "THE BEER-WARE LICENSE" (Revision 128) -# As long as you retain this notice you can do whatever you want with this stuff. -# If we meet some day, and you think this stuff is worth it, you can buy me a beer in return -# There is no warranty. -# - diff --git a/src/test/cpp/MemoryAlignment/nbproject/private/private.xml b/src/test/cpp/MemoryAlignment/nbproject/private/private.xml deleted file mode 100644 index c54ef76..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/private/private.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - 1 - 0 - - diff --git a/src/test/cpp/MemoryAlignment/nbproject/project.properties b/src/test/cpp/MemoryAlignment/nbproject/project.properties deleted file mode 100644 index bda28c6..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/project.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2011. Peter Lawrey -# -# "THE BEER-WARE LICENSE" (Revision 128) -# As long as you retain this notice you can do whatever you want with this stuff. -# If we meet some day, and you think this stuff is worth it, you can buy me a beer in return -# There is no warranty. -# - diff --git a/src/test/cpp/MemoryAlignment/nbproject/project.xml b/src/test/cpp/MemoryAlignment/nbproject/project.xml deleted file mode 100644 index 8f498fa..0000000 --- a/src/test/cpp/MemoryAlignment/nbproject/project.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - org.netbeans.modules.cnd.makeproject - - - MemoryAlignment - - cpp - - - - - - Debug - 1 - - - Release - 1 - - - UTF-8 - - - diff --git a/src/test/cpp/memorytest/.dep.inc b/src/test/cpp/memorytest/.dep.inc deleted file mode 100644 index 4560e55..0000000 --- a/src/test/cpp/memorytest/.dep.inc +++ /dev/null @@ -1,5 +0,0 @@ -# This code depends on make tool being used -DEPFILES=$(wildcard $(addsuffix .d, ${OBJECTFILES})) -ifneq (${DEPFILES},) -include ${DEPFILES} -endif diff --git a/src/test/cpp/memorytest/Makefile b/src/test/cpp/memorytest/Makefile deleted file mode 100644 index ec9de69..0000000 --- a/src/test/cpp/memorytest/Makefile +++ /dev/null @@ -1,128 +0,0 @@ -# -# There exist several targets which are by default empty and which can be -# used for execution of your targets. These targets are usually executed -# before and after some main targets. They are: -# -# .build-pre: called before 'build' target -# .build-post: called after 'build' target -# .clean-pre: called before 'clean' target -# .clean-post: called after 'clean' target -# .clobber-pre: called before 'clobber' target -# .clobber-post: called after 'clobber' target -# .all-pre: called before 'all' target -# .all-post: called after 'all' target -# .help-pre: called before 'help' target -# .help-post: called after 'help' target -# -# Targets beginning with '.' are not intended to be called on their own. -# -# Main targets can be executed directly, and they are: -# -# build build a specific configuration -# clean remove built files from a configuration -# clobber remove all built files -# all build all configurations -# help print help mesage -# -# Targets .build-impl, .clean-impl, .clobber-impl, .all-impl, and -# .help-impl are implemented in nbproject/makefile-impl.mk. -# -# Available make variables: -# -# CND_BASEDIR base directory for relative paths -# CND_DISTDIR default top distribution directory (build artifacts) -# CND_BUILDDIR default top build directory (object files, ...) -# CONF name of current configuration -# CND_PLATFORM_${CONF} platform name (current configuration) -# CND_ARTIFACT_DIR_${CONF} directory of build artifact (current configuration) -# CND_ARTIFACT_NAME_${CONF} name of build artifact (current configuration) -# CND_ARTIFACT_PATH_${CONF} path to build artifact (current configuration) -# CND_PACKAGE_DIR_${CONF} directory of package (current configuration) -# CND_PACKAGE_NAME_${CONF} name of package (current configuration) -# CND_PACKAGE_PATH_${CONF} path to package (current configuration) -# -# NOCDDL - - -# Environment -MKDIR=mkdir -CP=cp -CCADMIN=CCadmin - - -# build -build: .build-post - -.build-pre: -# Add your pre 'build' code here... - -.build-post: .build-impl -# Add your post 'build' code here... - - -# clean -clean: .clean-post - -.clean-pre: -# Add your pre 'clean' code here... - -.clean-post: .clean-impl -# Add your post 'clean' code here... - - -# clobber -clobber: .clobber-post - -.clobber-pre: -# Add your pre 'clobber' code here... - -.clobber-post: .clobber-impl -# Add your post 'clobber' code here... - - -# all -all: .all-post - -.all-pre: -# Add your pre 'all' code here... - -.all-post: .all-impl -# Add your post 'all' code here... - - -# build tests -build-tests: .build-tests-post - -.build-tests-pre: -# Add your pre 'build-tests' code here... - -.build-tests-post: .build-tests-impl -# Add your post 'build-tests' code here... - - -# run tests -test: .test-post - -.test-pre: -# Add your pre 'test' code here... - -.test-post: .test-impl -# Add your post 'test' code here... - - -# help -help: .help-post - -.help-pre: -# Add your pre 'help' code here... - -.help-post: .help-impl -# Add your post 'help' code here... - - - -# include project implementation makefile -include nbproject/Makefile-impl.mk - -# include project make variables -include nbproject/Makefile-variables.mk diff --git a/src/test/cpp/memorytest/main.cpp b/src/test/cpp/memorytest/main.cpp deleted file mode 100644 index 55f0b95..0000000 --- a/src/test/cpp/memorytest/main.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/* - * File: main.cpp - * Author: peter - * - * Created on 04 August 2011, 14:26 - */ - -#include -#include -#include -#include - -using namespace std; - -#define length (64LL * 1024 * 1024 * 1024) - -double diff(timeval a, timeval b) { - return a.tv_sec - b.tv_sec + (a.tv_usec - b.tv_usec) / 1e6; -} - -/* - * - */ -void timeBytesTest() { - - struct timeval init, mid1, mid2, final; - gettimeofday(&init, 0); - - // - char* bytes = new char[length]; - - gettimeofday(&mid1, 0); - for (long long i = 0; i < length; i++) - bytes[i] = (char) i; - - gettimeofday(&mid2, 0); - - for (long long i = 0; i < length; i++) { - char b = bytes[i]; - if (b != (char) i) { - cerr << "Expected " << (char) i << " but was " << b << endl; - return; - } - } - gettimeofday(&final, 0); - delete bytes; - - // - cout << "char[] took " - << diff(mid1, init)*1e6 << " usec to allocate and " - << diff(mid2, mid1) << " sec to write and " - << diff(final, mid2) << " sec to read" << endl; - return; -} - -void timeBytesUnrolledTest() { - - struct timeval init, mid1, mid2, final; - gettimeofday(&init, 0); - - // - char* bytes = new char[length]; - - gettimeofday(&mid1, 0); - for (long long i = 0; i < length; i += 4) { - bytes[i] = (char) i; - bytes[i + 1] = (char) (i + 1); - bytes[i + 2] = (char) (i + 2); - bytes[i + 3] = (char) (i + 3); - } - - gettimeofday(&mid2, 0); - - for (long long i = 0; i < length; i += 4) { - char b0 = bytes[i]; - char b1 = bytes[i + 1]; - char b2 = bytes[i + 2]; - char b3 = bytes[i + 3]; - if (b0 != (char) i) { - cerr << "Expected " << (char) i << " but was " << b0 << endl; - return; - } - if (b1 != (char) (i + 1)) { - cerr << "Expected " << (char) (i + 1) << " but was " << b1 << endl; - return; - } - if (b2 != (char) (i + 2)) { - cerr << "Expected " << (char) (i + 2) << " but was " << b2 << endl; - return; - } - if (b3 != (char) (i + 3)) { - cerr << "Expected " << (char) (i + 3) << " but was " << b3 << endl; - return; - } - } - gettimeofday(&final, 0); - delete bytes; - - // - cout << "char[] unrolled took " - << diff(mid1, init)*1e6 << " usec to allocate and " - << diff(mid2, mid1) << " sec to write and " - << diff(final, mid2) << " sec to read" << endl; - return; -} - -/* - * - */ -void timeLongTest() { - - struct timeval init, mid1, mid2, final; - gettimeofday(&init, 0); - - // - long long* longs = new long long[length/8]; - - gettimeofday(&mid1, 0); - for (long long i = 0; i < length/8; i++) - longs[i] = i; - - gettimeofday(&mid2, 0); - - for (long long i = 0; i < length/8; i++) { - long long l = longs[i]; - if (l != i) { - cerr << "Expected " << i << " but was " << l << endl; - return; - } - } - gettimeofday(&final, 0); - delete longs; - - // - cout << "long[] took " - << diff(mid1, init)*1e6 << " usec to allocate and " - << diff(mid2, mid1) << " sec to write and " - << diff(final, mid2) << " sec to read" << endl; - return; -} - - -void timeLongUnrolledTest() { - - struct timeval init, mid1, mid2, final; - gettimeofday(&init, 0); - - // - long long* longs = new long long[length/8]; - - gettimeofday(&mid1, 0); - for (long long i = 0; i < length/8; i += 4) { - longs[i] = i; - longs[i + 1] = i + 1; - longs[i + 2] = i + 2; - longs[i + 3] = i + 3; - } - - gettimeofday(&mid2, 0); - - for (long long i = 0; i < length/8; i += 4) { - long long b0 = longs[i]; - long long b1 = longs[i + 1]; - long long b2 = longs[i + 2]; - long long b3 = longs[i + 3]; - if (b0 != i) { - cerr << "Expected " << i << " but was " << b0 << endl; - return; - } - if (b1 != (i + 1)) { - cerr << "Expected " << (i + 1) << " but was " << b1 << endl; - return; - } - if (b2 != (i + 2)) { - cerr << "Expected " << (i + 2) << " but was " << b2 << endl; - return; - } - if (b3 != (i + 3)) { - cerr << "Expected " << (i + 3) << " but was " << b3 << endl; - return; - } - } - gettimeofday(&final, 0); - delete longs; - - // - cout << "long[] unrolled took " - << diff(mid1, init)*1e6 << " usec to allocate and " - << diff(mid2, mid1) << " sec to write and " - << diff(final, mid2) << " sec to read" << endl; - return; -} - -/* - * - */ -int main(int argc, char** argv) { -// timeBytesTest(); -// timeBytesUnrolledTest(); -// timeLongTest(); - timeLongUnrolledTest(); - return 0; -} diff --git a/src/test/cpp/memorytest/nbproject/Makefile-Debug.mk b/src/test/cpp/memorytest/nbproject/Makefile-Debug.mk deleted file mode 100644 index 8c7a6a4..0000000 --- a/src/test/cpp/memorytest/nbproject/Makefile-Debug.mk +++ /dev/null @@ -1,83 +0,0 @@ -# -# Generated Makefile - do not edit! -# -# Edit the Makefile in the project folder instead (../Makefile). Each target -# has a -pre and a -post target defined where you can add customized code. -# -# This makefile implements configuration specific macros and targets. - - -# Environment -MKDIR=mkdir -CP=cp -GREP=grep -NM=nm -CCADMIN=CCadmin -RANLIB=ranlib -CC=gcc -CCC=g++ -CXX=g++ -FC=gfortran -AS=as - -# Macros -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Debug -CND_DISTDIR=dist -CND_BUILDDIR=build - -# Include project Makefile -include Makefile - -# Object Directory -OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM} - -# Object Files -OBJECTFILES= \ - ${OBJECTDIR}/main.o - - -# C Compiler Flags -CFLAGS= - -# CC Compiler Flags -CCFLAGS= -CXXFLAGS= - -# Fortran Compiler Flags -FFLAGS= - -# Assembler Flags -ASFLAGS= - -# Link Libraries and Options -LDLIBSOPTIONS= - -# Build Targets -.build-conf: ${BUILD_SUBPROJECTS} - "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest - -${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest: ${OBJECTFILES} - ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} - ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest ${OBJECTFILES} ${LDLIBSOPTIONS} - -${OBJECTDIR}/main.o: main.cpp - ${MKDIR} -p ${OBJECTDIR} - ${RM} $@.d - $(COMPILE.cc) -g -MMD -MP -MF $@.d -o ${OBJECTDIR}/main.o main.cpp - -# Subprojects -.build-subprojects: - -# Clean Targets -.clean-conf: ${CLEAN_SUBPROJECTS} - ${RM} -r ${CND_BUILDDIR}/${CND_CONF} - ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest - -# Subprojects -.clean-subprojects: - -# Enable dependency checking -.dep.inc: .depcheck-impl - -include .dep.inc diff --git a/src/test/cpp/memorytest/nbproject/Makefile-Release.mk b/src/test/cpp/memorytest/nbproject/Makefile-Release.mk deleted file mode 100644 index 61f8cf0..0000000 --- a/src/test/cpp/memorytest/nbproject/Makefile-Release.mk +++ /dev/null @@ -1,83 +0,0 @@ -# -# Generated Makefile - do not edit! -# -# Edit the Makefile in the project folder instead (../Makefile). Each target -# has a -pre and a -post target defined where you can add customized code. -# -# This makefile implements configuration specific macros and targets. - - -# Environment -MKDIR=mkdir -CP=cp -GREP=grep -NM=nm -CCADMIN=CCadmin -RANLIB=ranlib -CC=gcc -CCC=g++ -CXX=g++ -FC=gfortran -AS=as - -# Macros -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Release -CND_DISTDIR=dist -CND_BUILDDIR=build - -# Include project Makefile -include Makefile - -# Object Directory -OBJECTDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM} - -# Object Files -OBJECTFILES= \ - ${OBJECTDIR}/main.o - - -# C Compiler Flags -CFLAGS= - -# CC Compiler Flags -CCFLAGS= -CXXFLAGS= - -# Fortran Compiler Flags -FFLAGS= - -# Assembler Flags -ASFLAGS= - -# Link Libraries and Options -LDLIBSOPTIONS= - -# Build Targets -.build-conf: ${BUILD_SUBPROJECTS} - "${MAKE}" -f nbproject/Makefile-${CND_CONF}.mk ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest - -${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest: ${OBJECTFILES} - ${MKDIR} -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM} - ${LINK.cc} -o ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest ${OBJECTFILES} ${LDLIBSOPTIONS} - -${OBJECTDIR}/main.o: main.cpp - ${MKDIR} -p ${OBJECTDIR} - ${RM} $@.d - $(COMPILE.cc) -O2 -MMD -MP -MF $@.d -o ${OBJECTDIR}/main.o main.cpp - -# Subprojects -.build-subprojects: - -# Clean Targets -.clean-conf: ${CLEAN_SUBPROJECTS} - ${RM} -r ${CND_BUILDDIR}/${CND_CONF} - ${RM} ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest - -# Subprojects -.clean-subprojects: - -# Enable dependency checking -.dep.inc: .depcheck-impl - -include .dep.inc diff --git a/src/test/cpp/memorytest/nbproject/Makefile-impl.mk b/src/test/cpp/memorytest/nbproject/Makefile-impl.mk deleted file mode 100644 index 004f8d1..0000000 --- a/src/test/cpp/memorytest/nbproject/Makefile-impl.mk +++ /dev/null @@ -1,133 +0,0 @@ -# -# Generated Makefile - do not edit! -# -# Edit the Makefile in the project folder instead (../Makefile). Each target -# has a pre- and a post- target defined where you can add customization code. -# -# This makefile implements macros and targets common to all configurations. -# -# NOCDDL - - -# Building and Cleaning subprojects are done by default, but can be controlled with the SUB -# macro. If SUB=no, subprojects will not be built or cleaned. The following macro -# statements set BUILD_SUB-CONF and CLEAN_SUB-CONF to .build-reqprojects-conf -# and .clean-reqprojects-conf unless SUB has the value 'no' -SUB_no=NO -SUBPROJECTS=${SUB_${SUB}} -BUILD_SUBPROJECTS_=.build-subprojects -BUILD_SUBPROJECTS_NO= -BUILD_SUBPROJECTS=${BUILD_SUBPROJECTS_${SUBPROJECTS}} -CLEAN_SUBPROJECTS_=.clean-subprojects -CLEAN_SUBPROJECTS_NO= -CLEAN_SUBPROJECTS=${CLEAN_SUBPROJECTS_${SUBPROJECTS}} - - -# Project Name -PROJECTNAME=memorytest - -# Active Configuration -DEFAULTCONF=Debug -CONF=${DEFAULTCONF} - -# All Configurations -ALLCONFS=Debug Release - - -# build -.build-impl: .build-pre .validate-impl .depcheck-impl - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .build-conf - - -# clean -.clean-impl: .clean-pre .validate-impl .depcheck-impl - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .clean-conf - - -# clobber -.clobber-impl: .clobber-pre .depcheck-impl - @#echo "=> Running $@..." - for CONF in ${ALLCONFS}; \ - do \ - "${MAKE}" -f nbproject/Makefile-$${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .clean-conf; \ - done - -# all -.all-impl: .all-pre .depcheck-impl - @#echo "=> Running $@..." - for CONF in ${ALLCONFS}; \ - do \ - "${MAKE}" -f nbproject/Makefile-$${CONF}.mk QMAKE=${QMAKE} SUBPROJECTS=${SUBPROJECTS} .build-conf; \ - done - -# build tests -.build-tests-impl: .build-impl .build-tests-pre - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk SUBPROJECTS=${SUBPROJECTS} .build-tests-conf - -# run tests -.test-impl: .build-tests-impl .test-pre - @#echo "=> Running $@... Configuration=$(CONF)" - "${MAKE}" -f nbproject/Makefile-${CONF}.mk SUBPROJECTS=${SUBPROJECTS} .test-conf - -# dependency checking support -.depcheck-impl: - @echo "# This code depends on make tool being used" >.dep.inc - @if [ -n "${MAKE_VERSION}" ]; then \ - echo "DEPFILES=\$$(wildcard \$$(addsuffix .d, \$${OBJECTFILES}))" >>.dep.inc; \ - echo "ifneq (\$${DEPFILES},)" >>.dep.inc; \ - echo "include \$${DEPFILES}" >>.dep.inc; \ - echo "endif" >>.dep.inc; \ - else \ - echo ".KEEP_STATE:" >>.dep.inc; \ - echo ".KEEP_STATE_FILE:.make.state.\$${CONF}" >>.dep.inc; \ - fi - -# configuration validation -.validate-impl: - @if [ ! -f nbproject/Makefile-${CONF}.mk ]; \ - then \ - echo ""; \ - echo "Error: can not find the makefile for configuration '${CONF}' in project ${PROJECTNAME}"; \ - echo "See 'make help' for details."; \ - echo "Current directory: " `pwd`; \ - echo ""; \ - fi - @if [ ! -f nbproject/Makefile-${CONF}.mk ]; \ - then \ - exit 1; \ - fi - - -# help -.help-impl: .help-pre - @echo "This makefile supports the following configurations:" - @echo " ${ALLCONFS}" - @echo "" - @echo "and the following targets:" - @echo " build (default target)" - @echo " clean" - @echo " clobber" - @echo " all" - @echo " help" - @echo "" - @echo "Makefile Usage:" - @echo " make [CONF=] [SUB=no] build" - @echo " make [CONF=] [SUB=no] clean" - @echo " make [SUB=no] clobber" - @echo " make [SUB=no] all" - @echo " make help" - @echo "" - @echo "Target 'build' will build a specific configuration and, unless 'SUB=no'," - @echo " also build subprojects." - @echo "Target 'clean' will clean a specific configuration and, unless 'SUB=no'," - @echo " also clean subprojects." - @echo "Target 'clobber' will remove all built files from all configurations and," - @echo " unless 'SUB=no', also from subprojects." - @echo "Target 'all' will will build all configurations and, unless 'SUB=no'," - @echo " also build subprojects." - @echo "Target 'help' prints this message." - @echo "" - diff --git a/src/test/cpp/memorytest/nbproject/Makefile-variables.mk b/src/test/cpp/memorytest/nbproject/Makefile-variables.mk deleted file mode 100644 index ac47e7f..0000000 --- a/src/test/cpp/memorytest/nbproject/Makefile-variables.mk +++ /dev/null @@ -1,35 +0,0 @@ -# -# Generated - do not edit! -# -# NOCDDL -# -CND_BASEDIR=`pwd` -CND_BUILDDIR=build -CND_DISTDIR=dist -# Debug configuration -CND_PLATFORM_Debug=GNU-Linux-x86 -CND_ARTIFACT_DIR_Debug=dist/Debug/GNU-Linux-x86 -CND_ARTIFACT_NAME_Debug=memorytest -CND_ARTIFACT_PATH_Debug=dist/Debug/GNU-Linux-x86/memorytest -CND_PACKAGE_DIR_Debug=dist/Debug/GNU-Linux-x86/package -CND_PACKAGE_NAME_Debug=memorytest.tar -CND_PACKAGE_PATH_Debug=dist/Debug/GNU-Linux-x86/package/memorytest.tar -# Release configuration -CND_PLATFORM_Release=GNU-Linux-x86 -CND_ARTIFACT_DIR_Release=dist/Release/GNU-Linux-x86 -CND_ARTIFACT_NAME_Release=memorytest -CND_ARTIFACT_PATH_Release=dist/Release/GNU-Linux-x86/memorytest -CND_PACKAGE_DIR_Release=dist/Release/GNU-Linux-x86/package -CND_PACKAGE_NAME_Release=memorytest.tar -CND_PACKAGE_PATH_Release=dist/Release/GNU-Linux-x86/package/memorytest.tar -# -# include compiler specific variables -# -# dmake command -ROOT:sh = test -f nbproject/private/Makefile-variables.mk || \ - (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk) -# -# gmake command -.PHONY: $(shell test -f nbproject/private/Makefile-variables.mk || (mkdir -p nbproject/private && touch nbproject/private/Makefile-variables.mk)) -# -include nbproject/private/Makefile-variables.mk diff --git a/src/test/cpp/memorytest/nbproject/Package-Debug.bash b/src/test/cpp/memorytest/nbproject/Package-Debug.bash deleted file mode 100644 index 256cdb9..0000000 --- a/src/test/cpp/memorytest/nbproject/Package-Debug.bash +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -x - -# -# Generated - do not edit! -# - -# Macros -TOP=`pwd` -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Debug -CND_DISTDIR=dist -CND_BUILDDIR=build -NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging -TMPDIRNAME=tmp-packaging -OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest -OUTPUT_BASENAME=memorytest -PACKAGE_TOP_DIR=memorytest/ - -# Functions -function checkReturnCode -{ - rc=$? - if [ $rc != 0 ] - then - exit $rc - fi -} -function makeDirectory -# $1 directory path -# $2 permission (optional) -{ - mkdir -p "$1" - checkReturnCode - if [ "$2" != "" ] - then - chmod $2 "$1" - checkReturnCode - fi -} -function copyFileToTmpDir -# $1 from-file path -# $2 to-file path -# $3 permission -{ - cp "$1" "$2" - checkReturnCode - if [ "$3" != "" ] - then - chmod $3 "$2" - checkReturnCode - fi -} - -# Setup -cd "${TOP}" -mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package -rm -rf ${NBTMPDIR} -mkdir -p ${NBTMPDIR} - -# Copy files and create directories and links -cd "${TOP}" -makeDirectory "${NBTMPDIR}/memorytest/bin" -copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 - - -# Generate tar file -cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memorytest.tar -cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memorytest.tar * -checkReturnCode - -# Cleanup -cd "${TOP}" -rm -rf ${NBTMPDIR} diff --git a/src/test/cpp/memorytest/nbproject/Package-Release.bash b/src/test/cpp/memorytest/nbproject/Package-Release.bash deleted file mode 100644 index 92d914d..0000000 --- a/src/test/cpp/memorytest/nbproject/Package-Release.bash +++ /dev/null @@ -1,75 +0,0 @@ -#!/bin/bash -x - -# -# Generated - do not edit! -# - -# Macros -TOP=`pwd` -CND_PLATFORM=GNU-Linux-x86 -CND_CONF=Release -CND_DISTDIR=dist -CND_BUILDDIR=build -NBTMPDIR=${CND_BUILDDIR}/${CND_CONF}/${CND_PLATFORM}/tmp-packaging -TMPDIRNAME=tmp-packaging -OUTPUT_PATH=${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/memorytest -OUTPUT_BASENAME=memorytest -PACKAGE_TOP_DIR=memorytest/ - -# Functions -function checkReturnCode -{ - rc=$? - if [ $rc != 0 ] - then - exit $rc - fi -} -function makeDirectory -# $1 directory path -# $2 permission (optional) -{ - mkdir -p "$1" - checkReturnCode - if [ "$2" != "" ] - then - chmod $2 "$1" - checkReturnCode - fi -} -function copyFileToTmpDir -# $1 from-file path -# $2 to-file path -# $3 permission -{ - cp "$1" "$2" - checkReturnCode - if [ "$3" != "" ] - then - chmod $3 "$2" - checkReturnCode - fi -} - -# Setup -cd "${TOP}" -mkdir -p ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package -rm -rf ${NBTMPDIR} -mkdir -p ${NBTMPDIR} - -# Copy files and create directories and links -cd "${TOP}" -makeDirectory "${NBTMPDIR}/memorytest/bin" -copyFileToTmpDir "${OUTPUT_PATH}" "${NBTMPDIR}/${PACKAGE_TOP_DIR}bin/${OUTPUT_BASENAME}" 0755 - - -# Generate tar file -cd "${TOP}" -rm -f ${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memorytest.tar -cd ${NBTMPDIR} -tar -vcf ../../../../${CND_DISTDIR}/${CND_CONF}/${CND_PLATFORM}/package/memorytest.tar * -checkReturnCode - -# Cleanup -cd "${TOP}" -rm -rf ${NBTMPDIR} diff --git a/src/test/cpp/memorytest/nbproject/configurations.xml b/src/test/cpp/memorytest/nbproject/configurations.xml deleted file mode 100644 index 6e9650d..0000000 --- a/src/test/cpp/memorytest/nbproject/configurations.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - main.cpp - - - - - Makefile - - - Makefile - - - - LOCAL_SOURCES - default - - - - - - - LOCAL_SOURCES - default - - - - 5 - - - 5 - - - 5 - - - 5 - - - - - diff --git a/src/test/cpp/memorytest/nbproject/private/Makefile-variables.mk b/src/test/cpp/memorytest/nbproject/private/Makefile-variables.mk deleted file mode 100644 index a64183e..0000000 --- a/src/test/cpp/memorytest/nbproject/private/Makefile-variables.mk +++ /dev/null @@ -1,7 +0,0 @@ -# -# Generated - do not edit! -# -# NOCDDL -# -# Debug configuration -# Release configuration diff --git a/src/test/cpp/memorytest/nbproject/private/configurations.xml b/src/test/cpp/memorytest/nbproject/private/configurations.xml deleted file mode 100644 index 7e35166..0000000 --- a/src/test/cpp/memorytest/nbproject/private/configurations.xml +++ /dev/null @@ -1,86 +0,0 @@ - - - - - Makefile - - - - localhost - 2 - - - - - - - - - - - - - - - - - gdb - - - - "${OUTPUT_PATH}" - - "${OUTPUT_PATH}" - - true - 0 - 0 - - - - - - - localhost - 2 - - - - - - - - - - - - - - - GizmoSimple - - - gdb - - - - "${OUTPUT_PATH}" - - "${OUTPUT_PATH}" - - true - 0 - 0 - - - - - - diff --git a/src/test/cpp/memorytest/nbproject/private/private.properties b/src/test/cpp/memorytest/nbproject/private/private.properties deleted file mode 100644 index bda28c6..0000000 --- a/src/test/cpp/memorytest/nbproject/private/private.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2011. Peter Lawrey -# -# "THE BEER-WARE LICENSE" (Revision 128) -# As long as you retain this notice you can do whatever you want with this stuff. -# If we meet some day, and you think this stuff is worth it, you can buy me a beer in return -# There is no warranty. -# - diff --git a/src/test/cpp/memorytest/nbproject/private/private.xml b/src/test/cpp/memorytest/nbproject/private/private.xml deleted file mode 100644 index d738a8b..0000000 --- a/src/test/cpp/memorytest/nbproject/private/private.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - 1 - 1 - - - diff --git a/src/test/cpp/memorytest/nbproject/project.properties b/src/test/cpp/memorytest/nbproject/project.properties deleted file mode 100644 index bda28c6..0000000 --- a/src/test/cpp/memorytest/nbproject/project.properties +++ /dev/null @@ -1,9 +0,0 @@ -# -# Copyright (c) 2011. Peter Lawrey -# -# "THE BEER-WARE LICENSE" (Revision 128) -# As long as you retain this notice you can do whatever you want with this stuff. -# If we meet some day, and you think this stuff is worth it, you can buy me a beer in return -# There is no warranty. -# - diff --git a/src/test/cpp/memorytest/nbproject/project.xml b/src/test/cpp/memorytest/nbproject/project.xml deleted file mode 100644 index 399f6bf..0000000 --- a/src/test/cpp/memorytest/nbproject/project.xml +++ /dev/null @@ -1,33 +0,0 @@ - - - - org.netbeans.modules.cnd.makeproject - - - memorytest - - cpp - - UTF-8 - - - - - Debug - 1 - - - Release - 1 - - - - - diff --git a/src/test/java/com/google/code/java/core/autoboxing/AutoBoxedWeakKeysMain.java b/src/test/java/com/google/code/java/core/autoboxing/AutoBoxedWeakKeysMain.java deleted file mode 100644 index 52dfaca..0000000 --- a/src/test/java/com/google/code/java/core/autoboxing/AutoBoxedWeakKeysMain.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.google.code.java.core.autoboxing; - -import java.util.Map; -import java.util.WeakHashMap; - -/** - * @author peter.lawrey - */ -public class AutoBoxedWeakKeysMain { - public static void main(String... args) { - Map keyValueMap = new WeakHashMap(10000); - for (long i = 1; i <= 8192; i *= 2) - keyValueMap.put(i, "key-" + i); - System.out.println("Before GC: " + keyValueMap); - System.gc(); - System.out.println("After GC: " + keyValueMap); - } -} diff --git a/src/test/java/com/google/code/java/core/autoboxing/AutoboxEqualsMain.java b/src/test/java/com/google/code/java/core/autoboxing/AutoboxEqualsMain.java deleted file mode 100644 index e2b466f..0000000 --- a/src/test/java/com/google/code/java/core/autoboxing/AutoboxEqualsMain.java +++ /dev/null @@ -1,157 +0,0 @@ -package com.google.code.java.core.autoboxing; - -/** - * @author peter.lawrey - */ -public class AutoboxEqualsMain { - public static void main(String... args) { - findAutoBoxedBoolean(); - findAutoBoxedBytes(); - findAutoBoxedChars(); - findAutoBoxedShort(); - findAutoBoxedIntegers(); - findAutoBoxedLong(); - findAutoBoxedFloat(); - findAutoBoxedDouble(); - } - - private static void findAutoBoxedBoolean() { - Boolean t1 = true; - Boolean t2 = true; - Boolean f1 = false; - Boolean f2 = false; - - if (t1 == t2 && f1 == f2) - System.out.println("All Boolean are cached."); - else - System.out.println("Not all Boolean are cached"); - } - - private static void findAutoBoxedBytes() { - byte first = 1, last = -1; - for (int i = 0; i >= Byte.MIN_VALUE; i--) { - Byte b1 = (byte) i; - Byte b2 = (byte) i; - if (b1 == b2) - first = (byte) i; - else break; - } - for (int i = 0; i <= Byte.MAX_VALUE; i++) { - Byte b1 = (byte) i; - Byte b2 = (byte) i; - if (b1 == b2) - last = (byte) i; - else break; - } - if (first == Byte.MIN_VALUE && last == Byte.MAX_VALUE) - System.out.println("All Byte are cached."); - else - System.out.println("The first auto-boxed byte is " + first + " and the last is " + last); - } - - private static void findAutoBoxedChars() { - char first = 1, last = 0; - for (int i = 0; i >= Character.MIN_VALUE; i--) { - Character b1 = (char) i; - Character b2 = (char) i; - if (b1 == b2) - first = (char) i; - else break; - } - for (int i = 0; i <= Character.MAX_VALUE; i++) { - Character b1 = (char) i; - Character b2 = (char) i; - if (b1 == b2) - last = (char) i; - else break; - } - if (first == Character.MIN_VALUE && last == Character.MAX_VALUE) - System.out.println("All Char are cached."); - else - System.out.println("The first auto-boxed char is " + (int) first + " and the last is " + (int) last); - } - - private static void findAutoBoxedShort() { - short first = 1, last = -1; - for (int i = 0; i >= Short.MIN_VALUE; i--) { - Short b1 = (short) i; - Short b2 = (short) i; - if (b1 == b2) - first = (short) i; - else break; - } - for (int i = 0; i <= Short.MAX_VALUE; i++) { - Short b1 = (short) i; - Short b2 = (short) i; - if (b1 == b2) - last = (short) i; - else break; - } - if (first == Short.MIN_VALUE && last == Short.MAX_VALUE) - System.out.println("All Short are cached."); - else - System.out.println("The first auto-boxed short is " + first + " and the last is " + last); - } - - private static void findAutoBoxedIntegers() { - int first = 1, last = -1; - for (long i = 0; i >= Integer.MIN_VALUE; i--) { - Integer b1 = (int) i; - Integer b2 = (int) i; - if (b1 == b2) - first = (int) i; - else break; - } - for (long i = 0; i <= Integer.MAX_VALUE; i++) { - Integer b1 = (int) i; - Integer b2 = (int) i; - if (b1 == b2) - last = (int) i; - else break; - } - if (first == Integer.MIN_VALUE && last == Integer.MAX_VALUE) - System.out.println("All Integer are cached."); - else - System.out.println("The first auto-boxed int is " + first + " and the last is " + last); - } - - private static void findAutoBoxedLong() { - long first = 1, last = -1; - for (int i = 0; i > Long.MIN_VALUE; i--) { - Long b1 = (long) i; - Long b2 = (long) i; - if (b1 == b2) - first = (long) i; - else break; - } - for (int i = 0; i < Long.MAX_VALUE; i++) { - Long b1 = (long) i; - Long b2 = (long) i; - if (b1 == b2) - last = (long) i; - else break; - } - if (first == Long.MIN_VALUE && last == Long.MAX_VALUE) - System.out.println("All Long are cached."); - else - System.out.println("The first auto-boxed long is " + first + " and the last is " + last); - } - - private static void findAutoBoxedFloat() { - Float f1 = 0.0f; - Float f2 = 0.0f; - if (f1 == f2) - System.out.println("Some Float are cached."); - else - System.out.println("No Float are cached."); - } - - private static void findAutoBoxedDouble() { - Double f1 = 0.0; - Double f2 = 0.0; - if (f1 == f2) - System.out.println("Some Double are cached."); - else - System.out.println("No Double are cached."); - } -} diff --git a/src/test/java/com/google/code/java/core/autoboxing/CompareIntArrayMain.java b/src/test/java/com/google/code/java/core/autoboxing/CompareIntArrayMain.java deleted file mode 100644 index cbb7359..0000000 --- a/src/test/java/com/google/code/java/core/autoboxing/CompareIntArrayMain.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.google.code.java.core.autoboxing; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author peter.lawrey - */ -public class CompareIntArrayMain { - public static void main(String... args) { - long used1 = usedMemory(); - int[] ints1 = new int[16000]; - for (int i = 0; i < ints1.length; i++) - ints1[i] = i; - long used2 = usedMemory(); - List ints2 = new ArrayList(ints1.length); - for (int i = 0; i < ints1.length; i++) - ints2.add(i); - long used3 = usedMemory(); - if (used3 - used1 < 80000) - System.out.println("You must use -XX:-UseTLAB to see small memory allocations"); - System.out.println("The int[" + ints1.length + "] took " + (used2 - used1) + " bytes and new ArrayList() with " + ints2.size() + " values took " + (used3 - used2) + " bytes"); - - } - - public static long usedMemory() { - return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); - } -} diff --git a/src/test/java/com/google/code/java/core/collections/AddIterateRemoveTest.java b/src/test/java/com/google/code/java/core/collections/AddIterateRemoveTest.java deleted file mode 100644 index 58b81ca..0000000 --- a/src/test/java/com/google/code/java/core/collections/AddIterateRemoveTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.collections; - -import org.junit.Test; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentSkipListMap; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CopyOnWriteArraySet; - -public class AddIterateRemoveTest { - static final int RUNS_TIME_MS = 10 * 1000; - static final int LARGEST_SIZE = 100 * 1000; - static final int[] INTS = new int[LARGEST_SIZE]; - - static { - for (int i = 0; i < LARGEST_SIZE; i++) INTS[i] = i; - } - - @Test - public void performanceTest() { - test(new TreeSet()); - test(Collections.synchronizedSortedSet(new TreeSet()), "synchronized TreeSet"); - test(new ArrayList()); - test(new LinkedList()); - test(new HashSet()); - test(new LinkedHashSet()); - test(Collections.newSetFromMap(new IdentityHashMap()), "newSetFromMap IdentityHashMap"); - test(Collections.newSetFromMap(new WeakHashMap()), "newSetFromMap WeakHashMap"); - - test(Collections.synchronizedList(new ArrayList()), "synchronized ArrayList"); - test(new Vector()); - test(Collections.synchronizedList(new LinkedList()), "synchronized LinkedList"); - test(Collections.synchronizedSet(new HashSet()), "synchronized HashSet"); - test(Collections.synchronizedSet(new LinkedHashSet()), "synchronized LinkedHashSet"); - test(new CopyOnWriteArrayList()); - test(new CopyOnWriteArraySet()); - test(Collections.newSetFromMap(new ConcurrentHashMap()), "newSetFromMap ConcurrentHashMap"); - test(Collections.newSetFromMap(new ConcurrentSkipListMap()), "newSetFromMap ConcurrentSkipListMap"); - } - - private void test(Collection ints) { - test(ints, ints.getClass().getSimpleName()); - } - - private void test(Collection ints, String collectionName) { - for (int size = LARGEST_SIZE; size >= 10; size /= 10) { - long adding = 0; - long removing = 0; - long iterating = 0; - - int runs = 0; - long endTime = System.currentTimeMillis() + RUNS_TIME_MS; - do { - runs++; - long start = System.nanoTime(); - testAdding(ints, size); - - adding += System.nanoTime() - start; - - start = System.nanoTime(); - for (int repeat = 0; repeat < 100; repeat++) - testIterating(ints); - iterating += System.nanoTime() - start; - - start = System.nanoTime(); - testRemoving(ints, size); - removing += (System.nanoTime() - start) * 2; - - ints.clear(); - } while (endTime > System.currentTimeMillis()); - System.out.println("" + collectionName - + "" + String.format("%,d", size) - + "" + format(10 * adding / runs / size) - + "" + format(iterating / runs / size) - + "" + format(10 * removing / runs / size) - + "" - ); - } - } - - private String format(long l) { - return l < 1000 ? "" + (l / 10.0) : l < 10000 ? "" + l / 10 : String.format("%,d", l / 10); - } - - private static void testAdding(Collection ints, int size) { - // adding - for (int i = 0; i < size; i++) - ints.add(INTS[i]); - } - - private static long testIterating(Collection ints) { - // iterating - long sum = 0; - for (Integer i : ints) - sum += i; - return sum; - } - - private void testRemoving(Collection ints, int size) { - // forward and reverse - for (int i = 0; i < size / 2; i++) { - ints.remove(INTS[i]); - ints.remove(INTS[size - i - 1]); - } - } -} diff --git a/src/test/java/com/google/code/java/core/collections/OrdersOfHashSet.java b/src/test/java/com/google/code/java/core/collections/OrdersOfHashSet.java deleted file mode 100644 index d304a74..0000000 --- a/src/test/java/com/google/code/java/core/collections/OrdersOfHashSet.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.collections; - -import org.junit.Test; - -import java.util.Arrays; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -public class OrdersOfHashSet { - @Test - public void testSetOrder() { - Set order = new HashSet(); - Collection elements = Arrays.asList("zero, one, two, three, four, five, six, seven, eight, nine, ten".split(", ")); - - try { - for (int i = 1; i > 0; i *= 2) { - Set set = new HashSet(i, 100); - set.addAll(elements); - String str = set.toString(); - if (order.add(str)) - System.out.println("HashSet(" + i + ") order was " + str); - } - } catch (OutOfMemoryError ignored) { - } - } -} diff --git a/src/test/java/com/google/code/java/core/datagram/DatagramPingTest.java b/src/test/java/com/google/code/java/core/datagram/DatagramPingTest.java deleted file mode 100644 index d69b1ee..0000000 --- a/src/test/java/com/google/code/java/core/datagram/DatagramPingTest.java +++ /dev/null @@ -1,222 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.datagram; - -import org.junit.Test; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedByInterruptException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.DatagramChannel; -import java.util.Arrays; - -public class DatagramPingTest { - - public static final int LENGTH = 512; - - @Test - public void testDatagramThroughput() throws IOException { - DatagramChannel dgc1 = DatagramChannel.open(); - InetSocketAddress addr1 = new InetSocketAddress(18888); - InetSocketAddress addr2 = new InetSocketAddress(28888); - dgc1.socket().bind(addr1); - dgc1.connect(addr2); - - DatagramChannel dgc2 = DatagramChannel.open(); - dgc2.socket().bind(addr2); - dgc2.connect(addr1); - - ByteBuffer bb1 = ByteBuffer.allocateDirect(LENGTH); - ByteBuffer bb2 = ByteBuffer.allocateDirect(LENGTH); - - long start = 0; - int runs = 1000000; - for (int i = -10000; i < runs; i++) { - if (i == 0) start = System.nanoTime(); - bb1.clear(); - dgc1.write(bb1); - - bb2.clear(); - int len = dgc2.read(bb2); - assert len == LENGTH; - bb2.flip(); - dgc2.write(bb2); - - bb1.clear(); - int len2 = dgc1.read(bb1); - assert len2 == LENGTH; -// System.out.println(len+" "+len2); - } - long time = System.nanoTime() - start; - dgc1.close(); - dgc2.close(); - System.out.printf("UDP Pings per second %,d K/s%n", runs * 1000000L / time); - } - - @Test - public void testDatagramLatency() throws IOException { - DatagramChannel dgc1 = DatagramChannel.open(); - InetSocketAddress addr1 = new InetSocketAddress(18888); - InetSocketAddress addr2 = new InetSocketAddress(28888); - dgc1.socket().bind(addr1); - dgc1.connect(addr2); - - DatagramChannel dgc2 = DatagramChannel.open(); - dgc2.socket().bind(addr2); - dgc2.connect(addr1); - - ByteBuffer bb1 = ByteBuffer.allocateDirect(LENGTH); - ByteBuffer bb2 = ByteBuffer.allocateDirect(LENGTH); - - int runs = 1000000; - int[] times = new int[runs]; - - for (int i = -10000; i < runs; i++) { - long start = System.nanoTime(); - bb1.clear(); - dgc1.write(bb1); - - bb2.clear(); - int len = dgc2.read(bb2); - assert len == LENGTH; - bb2.flip(); - dgc2.write(bb2); - - bb1.clear(); - int len2 = dgc1.read(bb1); - assert len2 == LENGTH; - if (i >= 0) - times[i] = (int) (System.nanoTime() - start); - } - dgc1.close(); - dgc2.close(); - Arrays.sort(times); - System.out.printf("UDP Pings latency was 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3); - } - - @Test - public void testThreadedPingThroughput() throws IOException, InterruptedException { - DatagramChannel dgc1 = DatagramChannel.open(); - InetSocketAddress addr1 = new InetSocketAddress(18888); - InetSocketAddress addr2 = new InetSocketAddress(28888); - dgc1.socket().bind(addr1); - dgc1.connect(addr2); - - final DatagramChannel dgc2 = DatagramChannel.open(); - dgc2.socket().bind(addr2); - dgc2.connect(addr1); - - Thread server = new Thread(new Runnable() { - public void run() { - try { - ByteBuffer bb2 = ByteBuffer.allocateDirect(LENGTH * 2); - while (!Thread.interrupted()) { - bb2.clear(); - dgc2.read(bb2); - bb2.flip(); - dgc2.write(bb2); - } - } catch (ClosedByInterruptException ignored) { - } catch (ClosedChannelException ignored) { - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - server.start(); - ByteBuffer bb1 = ByteBuffer.allocateDirect(LENGTH); - int runs = 1000 * 1000; - long start = 0; - for (int i = -20000; i < runs; i += 2) { - if (i == 0) start = System.nanoTime(); - bb1.clear(); - dgc1.write(bb1); - - bb1.clear(); - dgc1.write(bb1); - - bb1.clear(); - int len1 = dgc1.read(bb1); - assert len1 == LENGTH; - - bb1.clear(); - int len2 = dgc1.read(bb1); - assert len2 == LENGTH; - } - long time = System.nanoTime() - start; - server.interrupt(); - dgc1.close(); - dgc2.close(); - - System.out.printf("Threaded UDP Pings per second %,d K/s%n", runs * 1000000L / time); - } - - @Test - public void testThreadedPingLatency() throws IOException, InterruptedException { - DatagramChannel dgc1 = DatagramChannel.open(); - InetSocketAddress addr1 = new InetSocketAddress(18888); - InetSocketAddress addr2 = new InetSocketAddress(28888); - dgc1.socket().bind(addr1); - dgc1.connect(addr2); - - final DatagramChannel dgc2 = DatagramChannel.open(); - dgc2.socket().bind(addr2); - dgc2.connect(addr1); - - Thread server = new Thread(new Runnable() { - public void run() { - try { - ByteBuffer bb2 = ByteBuffer.allocateDirect(LENGTH); - while (!Thread.interrupted()) { - bb2.clear(); - int len = dgc2.read(bb2); - assert len == LENGTH; - bb2.flip(); - dgc2.write(bb2); - } - } catch (ClosedByInterruptException ignored) { - } catch (ClosedChannelException ignored) { - } catch (IOException e) { - e.printStackTrace(); - } - } - }); - server.start(); - ByteBuffer bb1 = ByteBuffer.allocateDirect(LENGTH); - int runs = 1000 * 1000; - int times[] = new int[runs]; - for (int i = -10000; i < times.length; i++) { - long start = System.nanoTime(); - bb1.clear(); - dgc1.write(bb1); - - bb1.clear(); - int len2 = dgc1.read(bb1); - assert len2 == LENGTH; - if (i >= 0) - times[i] = (int) (System.nanoTime() - start); - } - server.interrupt(); - dgc1.close(); - dgc2.close(); - - Arrays.sort(times); - System.out.printf("Threaded UDP Pings latency was 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3 - ); - } -} diff --git a/src/test/java/com/google/code/java/core/euler/LargestPalindromeMain.java b/src/test/java/com/google/code/java/core/euler/LargestPalindromeMain.java deleted file mode 100644 index 67b36c2..0000000 --- a/src/test/java/com/google/code/java/core/euler/LargestPalindromeMain.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.google.code.java.core.euler; - -import java.util.Arrays; - -/** - * @author peter.lawrey - */ -// 99956644665999 -public class LargestPalindromeMain { - public static void main(String... args) { - long start = System.nanoTime(); - for (int digits = 2; digits < 9; digits++) { - long[] solution = findLargestPalindromeProductForDigits(digits); - System.out.printf("The largest palindrome which is the product of two %d digit numbers is%n" + - "%,d * %,d = %,d%n", digits, solution[0], solution[1], solution[2]); - } - long time = System.nanoTime() - start; - System.out.printf("Solutions took %.3f seconds to find.%n", time / 1e9); - } - - private static long[] findLargestPalindromeProductForDigits(int n) { - long max = TENS[n] - 1; - long min = TENS[n - 1]; - - for (long i = max; i > min; i--) { - for (long j = max; j >= i; j--) { - long product = i * j; -// System.out.println(product); - if (isPalidrome(product)) { - long[] ret = {i, j, product}; - return ret; - } - } - } - throw new AssertionError("Unable to find a solution"); - } - - private static long[] TENS = new long[19]; - - static { - TENS[0] = 1; - for (int i = 1; i < TENS.length; i++) - TENS[i] = TENS[i - 1] * 10; - } - - private static long tens(long number) { - int tens = Arrays.binarySearch(TENS, number); - return TENS[tens < 0 ? ~tens - 1 : tens]; - } - - private static boolean isPalidrome(long number) { - long hiTens = tens(number); - long lowTens = 1; - while (hiTens > lowTens) { - long hiDigit = number / hiTens % 10; - long lowDigit = number / lowTens % 10; - if (hiDigit != lowDigit) - return false; - hiTens /= 10; - lowTens *= 10; - } - return true; - } -} diff --git a/src/test/java/com/google/code/java/core/euler/LongestSequenceMain.java b/src/test/java/com/google/code/java/core/euler/LongestSequenceMain.java deleted file mode 100644 index ee10c6d..0000000 --- a/src/test/java/com/google/code/java/core/euler/LongestSequenceMain.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.google.code.java.core.euler; - -/** - * @author peter.lawrey - */ -public class LongestSequenceMain { - public static void main(String... args) { - long start = System.nanoTime(); - int n = 700; - long[] result = findLongestSequence(n); - long time = System.nanoTime() - start; - System.out.printf("%,d has a sequence of length %,d, took %.3f seconds%n", result[1], result[0], time / 1e9); - } - - private static long[] findLongestSequence(int minLength) { - int length = 0; - long longest = 0; - for (long i = 1; length < minLength; i += 1) { - int length2 = getSequenceLength(i); - if (length2 > length) { - length = length2; - longest = i; - System.out.println(length + ": " + longest); - } - } - return new long[]{length, longest}; - } - - private static int getSequenceLength(long i) { - int count = 1; - while (i > 2) { - int mod4 = (int) (i & 3); - if (mod4 == 0) { - i = i / 4; - count += 2; - } else if (mod4 == 2) { - i = (i / 2) * 3 + 1; - count += 2; - } else { - i = (i * 3 + 1) / 2; - count += 2; - } - } - return count + (i == 2 ? 1 : 0); - } -} diff --git a/src/test/java/com/google/code/java/core/euler/LongestSequenceRecursiveMain.java b/src/test/java/com/google/code/java/core/euler/LongestSequenceRecursiveMain.java deleted file mode 100644 index fc5ccbb..0000000 --- a/src/test/java/com/google/code/java/core/euler/LongestSequenceRecursiveMain.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.google.code.java.core.euler; - -/** - * @author peter.lawrey - */ -public class LongestSequenceRecursiveMain { - public static void main(String... args) { - long start = System.nanoTime(); - int n = 1000; - long[] result = findLongestSequence(n); - long time = System.nanoTime() - start; - System.out.printf("%,d has a sequence of length %,d, took %.3f seconds%n", result[1], result[0], time / 1e9); - } - - private static long[] findLongestSequence(int minLength) { - int length = 0; - long longest = 0; - for (long i = 1; length < minLength; i += 1) { - int length2 = getSequenceLength(i); - if (length2 > length) { - length = length2; - longest = i; - System.out.println(length + ": " + longest); - } - } - return new long[]{length, longest}; - } - - private static final short[] SEQUENCE_LENGTH_CACHE = new short[1400 * 1000 * 1000]; - - private static int getSequenceLength(long n) { - long i = n; - if (i <= 2) - return i == 2 ? 2 : 1; - - if (n < SEQUENCE_LENGTH_CACHE.length) { - int length0 = SEQUENCE_LENGTH_CACHE[(int) n]; - if (length0 > 0) - return length0; - } - - int mod4 = (int) (i & 3); - if (mod4 == 0) { - i = i / 4; - } else if (mod4 == 2) { - i = (i / 2) * 3 + 1; - } else { - i = (i * 3 + 1) / 2; - } - int length = 2 + getSequenceLength(i); - if (n < SEQUENCE_LENGTH_CACHE.length) - SEQUENCE_LENGTH_CACHE[(int) n] = (short) length; - return length; - } -} diff --git a/src/test/java/com/google/code/java/core/euler/LongestSequenceRecursiveThreadedMain.java b/src/test/java/com/google/code/java/core/euler/LongestSequenceRecursiveThreadedMain.java deleted file mode 100644 index f14ac8d..0000000 --- a/src/test/java/com/google/code/java/core/euler/LongestSequenceRecursiveThreadedMain.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.google.code.java.core.euler; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * @author peter.lawrey - */ -public class LongestSequenceRecursiveThreadedMain { - public static void main(String... args) { - long start = System.nanoTime(); - int n = 1000; - long[] result = findLongestSequence(n); - long time = System.nanoTime() - start; - System.out.printf("%,d has a sequence of length %,d, took %.3f seconds%n", result[1], result[0], time / 1e9); - } - - private static long[] findLongestSequence(final int minLength) { - final int[] length = {0}; - final long[] longest = {0}; - final int processors = Runtime.getRuntime().availableProcessors(); - final ExecutorService es = Executors.newFixedThreadPool(processors); - for (int t = 0; t < processors; t++) { - final int finalT = t; - es.submit(new Runnable() { - @Override - public void run() { - long i; - for (i = 1 + 2 * finalT; length[0] < minLength; i += 2 * processors) { - int length2 = getSequenceLength(i); - if (length2 > length[0]) { - synchronized (length) { - if (length[0] < minLength && length2 > length[0]) { - length[0] = length2; - longest[0] = i; -// System.out.println(length[0] + ": " + longest[0]); - } - } - } - } - // backtrack as there could be an earlier solution than the one found. - synchronized (length) { - for (; i < longest[0]; i += 2 * processors) { - int length2 = getSequenceLength(i); - if (length2 > minLength && i < longest[0]) { - length[0] = length2; - longest[0] = i; -// System.out.println(length[0] + ": " + longest[0]); - } - } - } - } - }); - } - es.shutdown(); - try { - es.awaitTermination(1, TimeUnit.HOURS); - } catch (InterruptedException e) { - throw new AssertionError(e); - } - return new long[]{length[0], longest[0]}; - } - - private static final short[] SEQUENCE_LENGTH_CACHE = new short[1400 * 1000 * 1000]; - - private static int getSequenceLength(long n) { - long i = n; - if (i <= 2) - return i == 2 ? 2 : 1; - - if (n < SEQUENCE_LENGTH_CACHE.length) { - int length0 = SEQUENCE_LENGTH_CACHE[(int) n]; - if (length0 > 0) - return length0; - } - - int mod4 = (int) (i & 3); - if (mod4 == 0) { - i = i / 4; - } else if (mod4 == 2) { - i = (i / 2) * 3 + 1; - } else { - i = (i * 3 + 1) / 2; - } - int length = 2 + getSequenceLength(i); - if (n < SEQUENCE_LENGTH_CACHE.length) - SEQUENCE_LENGTH_CACHE[(int) n] = (short) length; - return length; - } -} diff --git a/src/test/java/com/google/code/java/core/euler/LongestSequenceThreadedMain.java b/src/test/java/com/google/code/java/core/euler/LongestSequenceThreadedMain.java deleted file mode 100644 index 7f9e66d..0000000 --- a/src/test/java/com/google/code/java/core/euler/LongestSequenceThreadedMain.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.google.code.java.core.euler; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -/** - * @author peter.lawrey - */ -public class LongestSequenceThreadedMain { - public static void main(String... args) { - long start = System.nanoTime(); - int n = 1000; - long[] result = findLongestSequence(n); - long time = System.nanoTime() - start; - System.out.printf("%,d has a sequence of length %,d, took %.3f seconds%n", result[1], result[0], time / 1e9); - } - - private static long[] findLongestSequence(final int minLength) { - final int[] length = {0}; - final long[] longest = {0}; - final int processors = Runtime.getRuntime().availableProcessors(); - final ExecutorService es = Executors.newFixedThreadPool(processors); - for (int t = 0; t < processors; t++) { - final int finalT = t; - es.submit(new Runnable() { - @Override - public void run() { - int localLongest = 0; - long i; - for (i = 1 + 2 * finalT; length[0] < minLength; i += 2 * processors) { - int length2 = getSequenceLength(i); - if (length2 > localLongest) { - synchronized (length) { - if (length2 > length[0]) { - length[0] = length2; - longest[0] = i; - System.out.println(length[0] + ": " + longest[0]); - } - localLongest = length[0]; - } - } - } - // backtrack as there could be an earlier solution than the one found. - synchronized (length) { - for (; i < longest[0]; i += 2 * processors) { - int length2 = getSequenceLength(i); - if (length2 > minLength && i < longest[0]) { - length[0] = length2; - longest[0] = i; - System.out.println(length[0] + ": " + longest[0]); - } - } - } - } - }); - } - es.shutdown(); - try { - es.awaitTermination(1, TimeUnit.HOURS); - } catch (InterruptedException e) { - throw new AssertionError(e); - } - return new long[]{length[0], longest[0]}; - } - - private static int getSequenceLength(long i) { - int count = 1; - while (i > 2) { - long mod4 = i & 3; - // multiple of 4. - if (mod4 == 0) { - i = i / 4; - count += 2; - - // multiple of 2 but not 4. - } else if (mod4 == 2) { - i = i / 2 * 3 + 1; - count += 2; - - // odd number. - } else { - i = (i * 3 + 1) / 2; - count += 2; - } - } - return count + (i == 2 ? 1 : 0); - } -} diff --git a/src/test/java/com/google/code/java/core/euler/SumEvenFibonacciMain.java b/src/test/java/com/google/code/java/core/euler/SumEvenFibonacciMain.java deleted file mode 100644 index a0ffec7..0000000 --- a/src/test/java/com/google/code/java/core/euler/SumEvenFibonacciMain.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.google.code.java.core.euler; - -/** - * @author peter.lawrey - */ -public class SumEvenFibonacciMain { - public static void main(String... args) { - long sum = largestLongSumOfEven(); - System.out.println("sum= " + sum); - } - - private static long largestLongSumOfEven() { - long sum = 0, x = 1, y = 1; - do { - long z = x + y; - // detect an overflow. - long nextSum = sum + z; - if ((long) (double) nextSum != nextSum) - break; - sum = nextSum; - x = y + z; - y = z + x; - } while (true); - return sum; - } -} diff --git a/src/test/java/com/google/code/java/core/executor/ExecutorTestMain.java b/src/test/java/com/google/code/java/core/executor/ExecutorTestMain.java deleted file mode 100644 index f755de4..0000000 --- a/src/test/java/com/google/code/java/core/executor/ExecutorTestMain.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.executor; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -public class ExecutorTestMain { - public static void main(String... args) { - int length = 1000 * 1000; - final double[] a = generate(length); - final double[] b = generate(length); - final double[] c = new double[length]; - - int nThreads = Runtime.getRuntime().availableProcessors(); - ExecutorService executor = Executors.newFixedThreadPool(nThreads); - - for (int i = 0; i < 5; i++) { - // single threaded - { - long start = System.nanoTime(); - geomean(a, b, c, 0, length); - long time = System.nanoTime() - start; - System.out.printf("Single threaded: Time to geomean %,d values was %.3f msecs. %n", length, time / 1e6); - } - // Too many tasks. - doTest(length, a, b, c, executor, 1, "Too many tasks"); - // Small number of tasks - doTest(length, a, b, c, executor, length / nThreads, "One task per thread"); - } - executor.shutdown(); - } - - private static void doTest(int length, final double[] a, final double[] b, final double[] c, ExecutorService executor, final int blockSize, String desc) { - List futures = new ArrayList(); - long start = System.nanoTime(); - for (int j = 0; j < length; j += blockSize) { - final int finalJ = j; - futures.add(executor.submit(new Runnable() { - @Override - public void run() { - geomean(a, b, c, finalJ, finalJ + blockSize); - } - })); - } - try { - for (Future future : futures) { - future.get(); - } - } catch (Exception e) { - throw new AssertionError(e); - } - long time = System.nanoTime() - start; - System.out.printf(desc + ": Time to geomean %,d values was %.3f msecs. %n", length, time / 1e6); - } - - private static double[] generate(int length) { - double[] d = new double[length]; - for (int i = 0; i < length; i++) - d[i] = Math.random() - Math.random(); - return d; - } - - public static void geomean(double[] a, double[] b, double[] c, int from, int to) { - for (int i = from; i < to; i++) - c[i] = Math.sqrt(a[i] * b[i]); - } -} diff --git a/src/test/java/com/google/code/java/core/files/FileReadingMain.java b/src/test/java/com/google/code/java/core/files/FileReadingMain.java deleted file mode 100644 index 90c7281..0000000 --- a/src/test/java/com/google/code/java/core/files/FileReadingMain.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.files; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; - -public class FileReadingMain { - public static void main(String... args) throws IOException { - File temp = File.createTempFile("deleteme", "zeros"); - FileOutputStream fos = new FileOutputStream(temp); - fos.write(new byte[50 * 1024 * 1024]); - fos.close(); - - for (int i = 0; i < 3; i++) - for (int blockSize = 1024 * 1024; blockSize >= 512; blockSize /= 2) { - readFileNIO(temp, blockSize); - readFile(temp, blockSize); - } - } - - private static void readFile(File temp, int blockSize) throws IOException { - long start = System.nanoTime(); - byte[] bytes = new byte[blockSize]; - int r; - for (r = 0; System.nanoTime() - start < 2e9; r++) { - FileInputStream fis = new FileInputStream(temp); - while (fis.read(bytes) > 0) ; - fis.close(); - } - long time = System.nanoTime() - start; - System.out.printf("IO: Reading took %.3f ms using %,d byte blocks%n", time / r / 1e6, blockSize); - } - - private static void readFileNIO(File temp, int blockSize) throws IOException { - long start = System.nanoTime(); - ByteBuffer bytes = ByteBuffer.allocateDirect(blockSize); - int r; - for (r = 0; System.nanoTime() - start < 2e9; r++) { - FileChannel fc = new FileInputStream(temp).getChannel(); - while (fc.read(bytes) > 0) { - bytes.clear(); - } - fc.close(); - } - long time = System.nanoTime() - start; - System.out.printf("NIO: Reading took %.3f ms using %,d byte blocks%n", time / r / 1e6, blockSize); - } -} diff --git a/src/test/java/com/google/code/java/core/files/MemoryMappedWritingMain.java b/src/test/java/com/google/code/java/core/files/MemoryMappedWritingMain.java deleted file mode 100644 index 48ea842..0000000 --- a/src/test/java/com/google/code/java/core/files/MemoryMappedWritingMain.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.files; - -import sun.nio.ch.DirectBuffer; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.ByteOrder; -import java.nio.IntBuffer; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; - -public class MemoryMappedWritingMain { - public static void main(String... args) throws IOException { - String dir = args[0]; - for (int i = 0; i < 24; i++) { - long start = System.nanoTime(); - File tmp = new File(dir, "deleteme." + i); - tmp.deleteOnExit(); - RandomAccessFile raf = new RandomAccessFile(tmp, "rw"); - final MappedByteBuffer map = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1 << 30); - IntBuffer array = map.order(ByteOrder.nativeOrder()).asIntBuffer(); - for (int n = 0; n < array.capacity(); n++) - array.put(n, n); - -// map.force(); - - ((DirectBuffer) map).cleaner().clean(); - raf.close(); - long time = System.nanoTime() - start; - System.out.printf("Took %.1f seconds to write 1 GB%n", time / 1e9); - } - } -} diff --git a/src/test/java/com/google/code/java/core/files/OpenCloseFilesTest.java b/src/test/java/com/google/code/java/core/files/OpenCloseFilesTest.java deleted file mode 100644 index d3815cb..0000000 --- a/src/test/java/com/google/code/java/core/files/OpenCloseFilesTest.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.files; - -import org.junit.Test; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import static junit.framework.Assert.assertTrue; - -public class OpenCloseFilesTest { - public static final String TMPFS_DIR = System.getProperty("tmpfs.dir", "/tmp/"); - private static final String LOCAL_FS_DIR = System.getProperty("user.home"); - public static final String NFS_DIR = System.getProperty("nfs.dir"); - - @Test - public void tmpfsPerfTest() throws IOException { - int files = 100 * 1000; - - // must be a tmpfs file system. - File dir = new File(TMPFS_DIR + "/deleteme"); - assertTrue(dir.mkdir()); - System.out.println("Created " + dir.getAbsolutePath()); - - byte[] bytes = new byte[256]; - long start = 0; - for (int i = -files / 10; i < files; i++) { - if (i == 0) start = System.nanoTime(); - File file = new File(dir, Integer.toString(i)); - FileOutputStream fos = new FileOutputStream(file); - fos.write(bytes); - fos.close(); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.1f us to write to TMPFS%n", time / 1e3 / files); - - long start2 = System.nanoTime(); - for (int i = -files / 10; i < files; i++) { - File file = new File(dir, Integer.toString(i)); - file.delete(); - } - assertTrue(dir.delete()); - long time2 = System.nanoTime() - start2; - System.out.println("Removed " + dir.getAbsolutePath()); - - System.out.printf("Took an average of %.1f us to delete files from TMPFS%n", time2 / 1e3 / (files + files / 10 + 1)); - - } - - @Test - public void localfsPerfTest() throws IOException { - int files = 10 * 1000; - - // must be a tmpfs file system. - File dir = new File(LOCAL_FS_DIR + "/deleteme"); - assertTrue(dir.mkdir()); - System.out.println("Created " + dir.getAbsolutePath()); - - byte[] bytes = new byte[256]; - long start = System.nanoTime(); - for (int i = 0; i < files; i++) { - File file = new File(dir, Integer.toString(i)); - FileOutputStream fos = new FileOutputStream(file); - fos.write(bytes); - fos.close(); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.1f us to write to LOCAL filesystem%n", time / 1e3 / files); - - long start2 = System.nanoTime(); - for (int i = 0; i < files; i++) { - File file = new File(dir, Integer.toString(i)); - file.delete(); - } - assertTrue(dir.delete()); - long time2 = System.nanoTime() - start2; - System.out.println("Removed " + dir.getAbsolutePath()); - - System.out.printf("Took an average of %.1f us to delete files from LOCAL filesystem%n", time2 / 1e3 / (files + 1)); - } - - @Test - public void nfsPerfTest() throws IOException { - int files = 250; - if (NFS_DIR == null) { - System.err.println("You must set -Dnfs.dir= to the location of a writable NFS drive to run this test"); - return; - } - - // must be a tmpfs file system. - File dir = new File(NFS_DIR + "/deleteme"); - assertTrue(dir.mkdir()); - System.out.println("Created " + dir.getAbsolutePath()); - - byte[] bytes = new byte[256]; - long start = 0; - for (int i = 0; i < files; i++) { - if (i == 0) start = System.nanoTime(); - File file = new File(dir, Integer.toString(i)); - FileOutputStream fos = new FileOutputStream(file); - fos.write(bytes); - fos.close(); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %,d us to write to the NFS drive%n", time / 1000 / files); - - long start2 = System.nanoTime(); - for (int i = 0; i < files; i++) { - File file = new File(dir, Integer.toString(i)); - file.delete(); - } - assertTrue(dir.delete()); - long time2 = System.nanoTime() - start2; - System.out.println("Removed " + dir.getAbsolutePath()); - - System.out.printf("Took an average of %,d us to delete files from the NFS drive%n", time2 / 1000 / (files + 1)); - } -} diff --git a/src/test/java/com/google/code/java/core/files/SharedMemoryReaderMain.java b/src/test/java/com/google/code/java/core/files/SharedMemoryReaderMain.java deleted file mode 100644 index b013fb5..0000000 --- a/src/test/java/com/google/code/java/core/files/SharedMemoryReaderMain.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.google.code.java.core.files; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.util.Arrays; - -/** - * @author peter.lawrey - */ -public class SharedMemoryReaderMain { - public static void main(String... args) throws IOException { - FileChannel fc = new RandomAccessFile("/tmp/deleteme.dat", "rw").getChannel(); - MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, SharedMemoryWriterMain.SIZE); - int[] latencies = new int[SharedMemoryWriterMain.SIZE / 8]; - int count = 0, waitcount = 0; - while (mbb.remaining() > 0) { - long l = mbb.getLong(mbb.position()); - if (l == 0) { - if (++waitcount % (int) 1e9 == 0) - System.out.println("read " + count); - continue; - } - long time = mbb.getLong(); - latencies[count++] = (int) (System.nanoTime() - time); - } - Arrays.sort(latencies); - System.out.printf("50/99/99.99%%tile %,d/%,d/%,d%n", - latencies[count / 2], - latencies[count - count / 100], - latencies[count - count / 10000] - ); - fc.close(); - } -} diff --git a/src/test/java/com/google/code/java/core/files/SharedMemoryWriterMain.java b/src/test/java/com/google/code/java/core/files/SharedMemoryWriterMain.java deleted file mode 100644 index 8acc76d..0000000 --- a/src/test/java/com/google/code/java/core/files/SharedMemoryWriterMain.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.google.code.java.core.files; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * @author peter.lawrey - */ -public class SharedMemoryWriterMain { - - public static final int SIZE = 1000 * 1024 * 1024; - - public static void main(String... args) throws IOException { - FileChannel fc = new RandomAccessFile("/tmp/deleteme.dat", "rw").getChannel(); - MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, SIZE); - AtomicBoolean flush = new AtomicBoolean(); - while (mbb.remaining() > 0) { - mbb.putLong(System.nanoTime()); - flush.set(true); - // pause - System.nanoTime(); - } - fc.close(); - } -} diff --git a/src/test/java/com/google/code/java/core/gc/DoubleCompareMain.java b/src/test/java/com/google/code/java/core/gc/DoubleCompareMain.java deleted file mode 100644 index 9142aef..0000000 --- a/src/test/java/com/google/code/java/core/gc/DoubleCompareMain.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.gc; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.PriorityQueue; - -public class DoubleCompareMain { - public static void main(String... args) { - List events = new ArrayList(); - for (int i = 0; i < 10000000; i++) - events.add(new ObjectWithDouble(Math.random())); - - doTest(events, Comparators.PRIMITIVE); - doTest(events, Comparators.OBJECT); - } - - private static double doTest(List events, Comparators comparator) { - long start = System.nanoTime(); - PriorityQueue pq = new PriorityQueue(events.size(), comparator); - pq.addAll(events); - double sum = 0; - while (!pq.isEmpty()) - sum += pq.poll().time; - long time = System.nanoTime() - start; - System.out.println(comparator + ": Took an average of " + time / events.size()); - return sum; - } -} - -enum Comparators implements Comparator { - PRIMITIVE { - @Override - public int compare(ObjectWithDouble o1, ObjectWithDouble o2) { - return Double.compare(o1.time, o2.time); - } - }, OBJECT { - @Override - public int compare(ObjectWithDouble o1, ObjectWithDouble o2) { - return new Double(o1.time).compareTo(o2.time); - } - } -} - -class ObjectWithDouble { - final double time; - - ObjectWithDouble(double time) { - this.time = time; - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/gc/GcPatternsTest.java b/src/test/java/com/google/code/java/core/gc/GcPatternsTest.java deleted file mode 100644 index 5752363..0000000 --- a/src/test/java/com/google/code/java/core/gc/GcPatternsTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.gc; - -import org.junit.Test; - -import java.util.LinkedList; -import java.util.List; - -public class GcPatternsTest { - // these test should be run with -verbosegc - @Test - public void createLotsOfSmallObjects() { - long start = System.nanoTime(); - while (System.nanoTime() - start < 20 * 60e9) { - for (int i = 0; i < 9000; i++) - new Object().hashCode(); - } - } - - @Test - public void createLotsOfLargeObject() { - long start = System.nanoTime(); - while (System.nanoTime() - start < 2e9) { - for (int i = 0; i < 1000; i++) - new byte[1024].hashCode(); - } - } - - @Test - public void createVariousLifeObjects() { - List shortList = new LinkedList(), - mediumList = new LinkedList(), - longList = new LinkedList(), - vlongList = new LinkedList(); - long start = System.nanoTime(); - while (System.nanoTime() - start < 60e9) { - for (int i = 0; i < 1000; i++) { - addToSize(shortList, 256 * 1024); // ~ 256 MB - if (i % 10 == 0) - addToSize(mediumList, 256 * 1024); // ~ 256 MB - if (i % 100 == 0) - addToSize(longList, 256 * 1024); // ~ 256 MB - if (i % 1000 == 0) - addToSize(vlongList, 256 * 1024); // ~ 256 MB - } - } - } - - private static void addToSize(List list, int maxSize) { - list.add(new byte[1000]); // ~1 KB with headers etc - if (list.size() > maxSize) - list.remove(0); - } -} diff --git a/src/test/java/com/google/code/java/core/gc/MemoryTest.java b/src/test/java/com/google/code/java/core/gc/MemoryTest.java deleted file mode 100644 index 6a9fee6..0000000 --- a/src/test/java/com/google/code/java/core/gc/MemoryTest.java +++ /dev/null @@ -1,767 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.gc; - -import org.junit.Test; -import sun.misc.Unsafe; - -import java.lang.reflect.Field; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; - -import static junit.framework.Assert.assertEquals; - -public class MemoryTest { - - public static final long MEMORY_TESTED = 24 * 1024 * 1024 * 1024L; - - @Test - public void hugeUnsafeMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - long address = UNSAFE.allocateMemory(length); - long time2 = System.nanoTime() - start2; - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - huWrite(length, address); - - long mid = System.nanoTime(); - System.out.println("reading"); - huRead(length, address); - long end = System.nanoTime(); - System.out.printf("Unsafe bytes took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - UNSAFE.freeMemory(address); - t.interrupt(); - } - } - - private static void huWrite(long length, long address) { - for (long l = 0; l < length; l++, address++) - UNSAFE.putByte(address, (byte) l); - } - - private static void huRead(long length, long address) { - for (long l = 0; l < length; l++, address++) { - byte b = UNSAFE.getByte(address); - if (b != (byte) l) - assertEquals((byte) l, b); - } - } - - @Test - public void hugeUnsafeUnrolledMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - long address = UNSAFE.allocateMemory(length); - long time2 = System.nanoTime() - start2; - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - huuWrite(length, address); - - long mid = System.nanoTime(); - System.out.println("reading"); - huuRead(length, address); - long end = System.nanoTime(); - System.out.printf("Unsafe bytes unrolled took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - UNSAFE.freeMemory(address); - t.interrupt(); - } - } - - private static void huuWrite(long length, long address) { - for (long l = 0; l < length; l += 8, address += 8) { - UNSAFE.putByte(address, (byte) l); - UNSAFE.putByte(address + 1, (byte) (l + 1)); - UNSAFE.putByte(address + 2, (byte) (l + 2)); - UNSAFE.putByte(address + 3, (byte) (l + 3)); - UNSAFE.putByte(address + 4, (byte) (l + 4)); - UNSAFE.putByte(address + 5, (byte) (l + 5)); - UNSAFE.putByte(address + 6, (byte) (l + 6)); - UNSAFE.putByte(address + 7, (byte) (l + 7)); - } - } - - private static void huuRead(long length, long address) { - for (long l = 0; l < length; l += 8, address += 8) { - byte b = UNSAFE.getByte(address); - byte b1 = UNSAFE.getByte(address + 1); - byte b2 = UNSAFE.getByte(address + 2); - byte b3 = UNSAFE.getByte(address + 3); - byte b4 = UNSAFE.getByte(address + 4); - byte b5 = UNSAFE.getByte(address + 5); - byte b6 = UNSAFE.getByte(address + 6); - byte b7 = UNSAFE.getByte(address + 7); - if (b != (byte) l) - assertEquals((byte) l, b); - if (b1 != (byte) (l + 1)) - assertEquals((byte) (l + 1), b); - if (b2 != (byte) (l + 2)) - assertEquals((byte) (l + 2), b); - if (b3 != (byte) (l + 3)) - assertEquals((byte) (l + 3), b); - if (b4 != (byte) (l + 4)) - assertEquals((byte) (l + 4), b); - if (b5 != (byte) (l + 5)) - assertEquals((byte) (l + 5), b); - if (b6 != (byte) (l + 6)) - assertEquals((byte) (l + 6), b); - if (b7 != (byte) (l + 7)) - assertEquals((byte) (l + 7), b); - } - } - - @Test - public void hugeUnsafeLongMemoryPerformance() throws InterruptedException { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - long address = UNSAFE.allocateMemory(length / 2); - long address2 = UNSAFE.allocateMemory(length / 2); - long time2 = System.nanoTime() - start2; - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - int count = 0; - for (long l = 0; l < length / 2; l += 1024 * 1024) { - luWrite(1024 * 1024, address + l); - luWrite(1024 * 1024, address2 + l); - if (l > 20 * 1024 * 1024 * 1024L) - Thread.sleep(20); - count += 2; - if (count % 10 == 0) System.out.println(count); - } - - long mid = System.nanoTime(); - System.out.println("reading"); - count = 0; - for (long l = 0; l < length / 2; l += 1024 * 1024) { - luRead(1024 * 1024, address + l); - luRead(1024 * 1024, address2 + l); - Thread.sleep(20); - count += 2; - if (count % 10 == 0) System.out.println(count); - } - long end = System.nanoTime(); - System.out.printf("Unsafe long Took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - UNSAFE.freeMemory(address); - t.interrupt(); - } - } - - private void luWrite(long length, long address) { - for (long l = 0; l < length; l += 8, address += 8) - UNSAFE.putLong(address, l); - } - - private static void luRead(long length, long address) { - for (long l = 0; l < length; l += 8, address += 8) { - long l2 = UNSAFE.getLong(address); - if (l != l2) - assertEquals(l, l2); - } - } - - @Test - public void hugeUnsafeLongUnrolledMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - long address = UNSAFE.allocateMemory(length); - long time2 = System.nanoTime() - start2; - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - luuWrite(length, address); - - long mid = System.nanoTime(); - System.out.println("reading"); - luuRead(length, address); - long end = System.nanoTime(); - System.out.printf("Unsafe long unrolled took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - UNSAFE.freeMemory(address); - t.interrupt(); - } - } - - private static void luuWrite(long length, long address) { - for (long l = 0; l < length - 24; l += 32, address += 32) { - UNSAFE.putLong(address, l); - UNSAFE.putLong(address + 8, l + 8); - UNSAFE.putLong(address + 16, l + 16); - UNSAFE.putLong(address + 24, l + 24); - } - } - - private static void luuRead(long length, long address) { - for (long l = 0; l < length - 24; l += 32, address += 32) { - long l0 = UNSAFE.getLong(address); - long l1 = UNSAFE.getLong(address + 8); - long l2 = UNSAFE.getLong(address + 16); - long l3 = UNSAFE.getLong(address + 24); - if (l != l0) - assertEquals(l, l0); - if (l + 8 != l1) - assertEquals(l + 8, l1); - if (l + 16 != l2) - assertEquals(l + 16, l2); - if (l + 24 != l3) - assertEquals(l + 24, l3); - } - } - - private static Thread monitorThread() { - Thread t = new Thread(new Runnable() { - @Override - public void run() { - long start = System.currentTimeMillis(); - while (!Thread.interrupted()) { - System.out.println((System.currentTimeMillis() - start) / 1000 - + " sec - " + - (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 - + " KB used"); - try { - Thread.sleep(10000); - } catch (InterruptedException ignored) { - break; - } - } - } - }); - t.setDaemon(true); - t.start(); - return t; - } - - @Test - public void hugeByteBufferMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - ByteBuffer[] buffers = new ByteBuffer[16]; - for (int i = 0; i < buffers.length; i++) - buffers[i] = ByteBuffer.allocateDirect((int) (length / 16)).order(ByteOrder.nativeOrder()); - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - bbWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - bbRead(buffers); - long end = System.nanoTime(); - System.out.printf("ByteBuffer byte took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private void bbWrite(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j++) { - buffer.put((byte) j); - } - } - } - - private void bbRead(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - buffer.flip(); - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j++) { - byte b = buffer.get(); - if (b != (byte) j) - assertEquals((byte) j, b); - } - } - } - - @Test - public void hugeByteBufferUnrolledMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - ByteBuffer[] buffers = new ByteBuffer[16]; - for (int i = 0; i < buffers.length; i++) - buffers[i] = ByteBuffer.allocateDirect((int) (length / 16)).order(ByteOrder.nativeOrder()); - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - bbuWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - bbuRead(buffers); - long end = System.nanoTime(); - System.out.printf("ByteBuffer byte unrolled took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void bbuWrite(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j += 4) { - buffer.put(j, (byte) j); - buffer.put(j + 1, (byte) (j + 1)); - buffer.put(j + 2, (byte) (j + 2)); - buffer.put(j + 3, (byte) (j + 3)); - } - } - } - - private static void bbuRead(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j += 4) { - byte b = buffer.get(j); - byte b1 = buffer.get(j + 1); - byte b2 = buffer.get(j + 2); - byte b3 = buffer.get(j + 3); - if (b != (byte) j) - assertEquals((byte) j, b); - if (b1 != (byte) (j + 1)) - assertEquals((byte) (j + 1), b1); - if (b2 != (byte) (j + 2)) - assertEquals((byte) (j + 2), b2); - if (b3 != (byte) (j + 3)) - assertEquals((byte) (j + 3), b3); - } - } - } - - @Test - public void hugeByteBufferLongMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - ByteBuffer[] buffers = new ByteBuffer[16]; - for (int i = 0; i < buffers.length; i++) - buffers[i] = ByteBuffer.allocateDirect((int) (length / 16)).order(ByteOrder.nativeOrder()); - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - lbWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - lbRead(buffers); - long end = System.nanoTime(); - System.out.printf("ByteBuffer long took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void lbWrite(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j += 8) { - buffer.putLong(j); - } - } - } - - private static void lbRead(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - buffer.flip(); - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j += 8) { - long l2 = buffer.getLong(); - if (j != l2) - assertEquals(j, l2); - } - } - } - - @Test - public void hugeByteBufferLongUnrolledMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - ByteBuffer[] buffers = new ByteBuffer[16]; - for (int i = 0; i < buffers.length; i++) - buffers[i] = ByteBuffer.allocateDirect((int) (length / 16)).order(ByteOrder.nativeOrder()); - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - lbuWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - lbuRead(buffers); - long end = System.nanoTime(); - System.out.printf("ByteBuffer long unrolled took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void lbuWrite(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j += 32) { - buffer.putLong(j, j); - buffer.putLong(j + 8, j + 8); - buffer.putLong(j + 16, j + 16); - buffer.putLong(j + 24, j + 24); - } - } - } - - private static void lbuRead(ByteBuffer[] buffers) { - for (int i = 0; i < buffers.length; i++) { - ByteBuffer buffer = buffers[i]; - int capacity = buffers[i].capacity(); - for (int j = 0; j < capacity; j += 32) { - long l0 = buffer.getLong(j); - long l1 = buffer.getLong(j + 8); - long l2 = buffer.getLong(j + 16); - long l3 = buffer.getLong(j + 24); - if (j != l0) - assertEquals(j, l0); - if (j + 8 != l1) - assertEquals(j + 8, l1); - if (j + 16 != l2) - assertEquals(j + 16, l2); - if (j + 24 != l3) - assertEquals(j + 24, l3); - } - } - } - - @Test - public void hugeByteArrayMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - byte[][] buffers = new byte[16][]; - for (int i = 0; i < buffers.length; i++) { - System.out.println(i + ": " + Runtime.getRuntime().totalMemory() + " free " + Runtime.getRuntime().freeMemory()); - buffers[i] = new byte[(int) (length / 16)]; - } - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - baWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - baRead(buffers); - long end = System.nanoTime(); - System.out.printf("byte[] took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void baWrite(byte[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - byte[] bytes = buffers[i]; - int capacity = bytes.length; - for (int j = 0; j < capacity; j++) { - bytes[j] = (byte) j; - } - } - } - - private static void baRead(byte[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - byte[] bytes = buffers[i]; - int capacity = bytes.length; - for (int j = 0; j < capacity; j++) { - byte b = bytes[j]; - if (b != (byte) j) - assertEquals((byte) j, b); - } - } - } - - @Test - public void hugeByteArrayUnrolledMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - byte[][] buffers = new byte[16][]; - for (int i = 0; i < buffers.length; i++) { - buffers[i] = new byte[(int) (length / 16)]; - } - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - bauWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - bauRead(buffers); - long end = System.nanoTime(); - System.out.printf("byte[] unrolled took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void bauRead(byte[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - byte[] bytes = buffers[i]; - int capacity = bytes.length; - for (int j = 0; j < capacity; j += 4) { - byte b = bytes[j]; - byte b1 = bytes[j + 1]; - byte b2 = bytes[j + 2]; - byte b3 = bytes[j + 3]; - if (b != (byte) j) - assertEquals((byte) j, b); - if (b1 != (byte) (j + 1)) - assertEquals((byte) (j + 1), b1); - if (b2 != (byte) (j + 2)) - assertEquals((byte) (j + 2), b2); - if (b3 != (byte) (j + 3)) - assertEquals((byte) (j + 3), b3); - } - } - } - - private static void bauWrite(byte[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - byte[] bytes = buffers[i]; - int capacity = bytes.length; - for (int j = 0; j < capacity; j += 4) { - bytes[j] = (byte) j; - bytes[j + 1] = (byte) (j + 1); - bytes[j + 2] = (byte) (j + 2); - bytes[j + 3] = (byte) (j + 3); - } - } - } - - @Test - public void hugeByteArrayLongMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - long[][] buffers = new long[16][]; - for (int i = 0; i < buffers.length; i++) - buffers[i] = new long[(int) (length / 16 / 8)]; - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - laWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - laRead(buffers); - long end = System.nanoTime(); - System.out.printf("long[] took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void laWrite(long[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - long[] longs = buffers[i]; - int capacity = longs.length; - for (int j = 0; j < capacity; j++) - longs[j] = j; - } - } - - private static void laRead(long[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - long[] longs = buffers[i]; - int capacity = buffers[i].length; - for (int j = 0; j < capacity; j++) { - long b = longs[j]; - if (j != b) - assertEquals(j, b); - } - } - } - - @Test - public void hugeByteArrayLongUnrolledMemoryPerformance() { - Thread t = monitorThread(); - - final long length = MEMORY_TESTED; - System.out.println("allocate"); - long start2 = System.nanoTime(); - long[][] buffers = new long[16][]; - for (int i = 0; i < buffers.length; i++) - buffers[i] = new long[(int) (length / 16 / 8)]; - long time2 = System.nanoTime() - start2; - - try { - // add a GC to see what the GC times are like. - System.gc(); - - long start = System.nanoTime(); - System.out.println("writing"); - lauWrite(buffers); - - long mid = System.nanoTime(); - System.out.println("reading"); - lauRead(buffers); - long end = System.nanoTime(); - System.out.printf("long[] unrolled took %,d us to allocate, %,d us to write and %,d us to read%n", - time2 / 1000, (mid - start) / 1000, (end - mid) / 1000); - } finally { - t.interrupt(); - System.gc(); - } - } - - private static void lauWrite(long[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - long[] longs = buffers[i]; - int capacity = longs.length; - for (int j = 0; j < capacity; j += 4) { - longs[j] = j; - longs[j + 1] = j + 1; - longs[j + 2] = j + 2; - longs[j + 3] = j + 3; - } - } - } - - private static void lauRead(long[][] buffers) { - for (int i = 0; i < buffers.length; i++) { - long[] longs = buffers[i]; - int capacity = buffers[i].length; - for (int j = 0; j < capacity; j += 4) { - long l0 = longs[j]; - long l1 = longs[j + 1]; - long l2 = longs[j + 2]; - long l3 = longs[j + 3]; - if (j != l0) - assertEquals(j, l0); - if (j + 1 != l1) - assertEquals(j + 1, l1); - if (j + 2 != l2) - assertEquals(j + 2, l2); - if (j + 3 != l3) - assertEquals(j + 3, l3); - } - } - } - - public static final Unsafe UNSAFE; static { - try { - Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); - theUnsafe.setAccessible(true); - UNSAFE = (Unsafe) theUnsafe.get(null); - } catch (Exception e) { - throw new AssertionError(e); - } - } -} diff --git a/src/test/java/com/google/code/java/core/gc/OrderOfObjectsAfterGCMain.java b/src/test/java/com/google/code/java/core/gc/OrderOfObjectsAfterGCMain.java deleted file mode 100644 index 0e1dd88..0000000 --- a/src/test/java/com/google/code/java/core/gc/OrderOfObjectsAfterGCMain.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.gc; - -import sun.misc.Unsafe; - -import java.lang.reflect.Field; -import java.util.Arrays; -import java.util.Collections; - -public class OrderOfObjectsAfterGCMain { - static final Unsafe unsafe = getUnsafe(); - static final boolean is64bit = true; // auto detect if possible. - - public static void main(String... args) { - Integer[] ascending = new Integer[16]; - for (int i = 0; i < ascending.length; i++) - ascending[i] = i; - - Integer[] descending = new Integer[16]; - for (int i = descending.length - 1; i >= 0; i--) - descending[i] = i; - - Integer[] shuffled = new Integer[16]; - for (int i = 0; i < shuffled.length; i++) - shuffled[i] = i; - Collections.shuffle(Arrays.asList(shuffled)); - - System.out.println("Before GC"); - printAddresses("ascending", ascending); - printAddresses("descending", descending); - printAddresses("shuffled", shuffled); - - System.gc(); - System.out.println("\nAfter GC"); - printAddresses("ascending", ascending); - printAddresses("descending", descending); - printAddresses("shuffled", shuffled); - - System.gc(); - System.out.println("\nAfter GC 2"); - printAddresses("ascending", ascending); - printAddresses("descending", descending); - printAddresses("shuffled", shuffled); - } - - public static void printAddresses(String label, Object... objects) { - System.out.print(label + ": 0x"); - long last = 0; - int offset = unsafe.arrayBaseOffset(objects.getClass()); - int scale = unsafe.arrayIndexScale(objects.getClass()); - switch (scale) { - case 4: - long factor = is64bit ? 8 : 1; - final long i1 = (unsafe.getInt(objects, offset) & 0xFFFFFFFFL) * factor; - System.out.print(Long.toHexString(i1)); - last = i1; - for (int i = 1; i < objects.length; i++) { - final long i2 = (unsafe.getInt(objects, offset + i * 4) & 0xFFFFFFFFL) * factor; - if (i2 > last) - System.out.print(", +" + Long.toHexString(i2 - last)); - else - System.out.print(", -" + Long.toHexString(last - i2)); - last = i2; - } - break; - case 8: - throw new AssertionError("Not supported"); - } - System.out.println(); - } - - private static Unsafe getUnsafe() { - try { - Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe"); - theUnsafe.setAccessible(true); - return (Unsafe) theUnsafe.get(null); - } catch (Exception e) { - throw new AssertionError(e); - } - } -} - diff --git a/src/test/java/com/google/code/java/core/io/BufferReaderTest.java b/src/test/java/com/google/code/java/core/io/BufferReaderTest.java deleted file mode 100644 index c987c88..0000000 --- a/src/test/java/com/google/code/java/core/io/BufferReaderTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2012. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.io; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; -import java.util.Arrays; - -public class BufferReaderTest { - public static final int size = 2047 * 1024 * 1024; - - public static void main(String... args) throws IOException { - RandomAccessFile raf = new RandomAccessFile("/d/peter/deleteme.dat", "rw"); - MappedByteBuffer mbb = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, size); - int[] times = new int[size / 8 / 16]; - int counter = 0; - int waiting = 0; - long start = 0; - while (mbb.remaining() > 0 && counter < times.length) { - long value = mbb.getLong(mbb.position()); - if ((++waiting & ((1 << 29) - 1)) == 0) - System.out.println("Counter: " + counter); - if (value < 0) { - System.out.println("EOF"); - break; - } else if (value == 0) { - continue; - } - if (start == 0) - start = System.nanoTime(); - - mbb.position(mbb.position() + 8 * 16); - times[counter++] = (int) (System.nanoTime() - value); - } - long time = System.nanoTime() - start; - if (mbb.remaining() <= 0) - System.out.println("end"); - if (counter == times.length) - System.out.println("remaining: " + mbb.remaining()); - raf.close(); - Arrays.sort(times); - System.out.printf("0/1/50/99/99.9/99.99%% latency was %,d/%,d/%,d/%,d/%,d/%,d%n", - times[0], - times[counter / 99], - times[counter / 2], - times[counter - counter / 100], - times[counter - counter / 1000], - times[counter - counter / 10000] - ); - System.out.printf("Throughput %.1f M msg/s%n", counter * 1e3 / time); - } -} diff --git a/src/test/java/com/google/code/java/core/io/BufferTest.java b/src/test/java/com/google/code/java/core/io/BufferTest.java deleted file mode 100644 index c26b272..0000000 --- a/src/test/java/com/google/code/java/core/io/BufferTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (c) 2012. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.io; - -import org.junit.Test; - -import java.io.*; - -public class BufferTest { - public static final double RUN_TIME_NS = 1e9; - - @Test - public void testBufferPerformance() throws IOException { - for (int i = 1; i <= 1024 * 1024; i *= 2) { - testBufferSize(i); - } - } - - private static void testBufferSize(int size) throws IOException { - int fileSize = 16 * 1024 * 1024; - - byte[] bytes = new byte[size]; - File tmpFile = File.createTempFile("deleteme", "zeros"); - tmpFile.deleteOnExit(); - - // test writing an unbuffered file. - int count1 = 0; - long start1 = System.nanoTime(); - do { - count1++; - OutputStream out = new FileOutputStream(tmpFile); - for (int i = 0; i < fileSize; i += size) - out.write(bytes); - out.close(); - } while (start1 + RUN_TIME_NS > System.nanoTime()); - long time1 = (System.nanoTime() - start1) / count1; - - // test writing a buffered file. - int count2 = 0; - long start2 = System.nanoTime(); - do { - count2++; - OutputStream out = new BufferedOutputStream(new FileOutputStream(tmpFile)); - for (int i = 0; i < fileSize; i += size) - out.write(bytes); - out.close(); - } while (start2 + RUN_TIME_NS > System.nanoTime()); - long time2 = (System.nanoTime() - start2) / count2; - - // test reading unbuffered file. - int count3 = 0; - long start3 = System.nanoTime(); - do { - count3++; - InputStream in = new FileInputStream(tmpFile); - while (in.read(bytes) > 0) ; - in.close(); - } while (start3 + RUN_TIME_NS > System.nanoTime()); - long time3 = (System.nanoTime() - start3) / count3; - - // test reading buffered file. - int count4 = 0; - long start4 = System.nanoTime(); - do { - count4++; - InputStream in = new BufferedInputStream(new FileInputStream(tmpFile)); - while (in.read(bytes) > 0) ; - in.close(); - } while (start4 + RUN_TIME_NS > System.nanoTime()); - long time4 = (System.nanoTime() - start4) / count4; - - long factor = 16 * 1000 * 1000 * 1000L; // 16 MB/ns in MB/s - System.out.printf("%,d" - + "%,d MB/s" - + "%,d MB/s" - + "%,d MB/s" - + "%,d MB/s" - + "%n", size, - factor / time1, factor / time2, factor / time3, factor / time4 - ); - } -} diff --git a/src/test/java/com/google/code/java/core/io/BufferWriterTest.java b/src/test/java/com/google/code/java/core/io/BufferWriterTest.java deleted file mode 100644 index f25c37f..0000000 --- a/src/test/java/com/google/code/java/core/io/BufferWriterTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2012. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.io; - -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.MappedByteBuffer; -import java.nio.channels.FileChannel; - -public class BufferWriterTest { - public static final int size = 2047 * 1024 * 1024; - private static volatile long flush = 0; - - public static void main(String... args) throws IOException { - RandomAccessFile raf = new RandomAccessFile("/tmp/deleteme.dat", "rw"); - MappedByteBuffer mbb = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, size); - long start = System.nanoTime(); - final long now = System.nanoTime(); - while (mbb.remaining() > 0) { - mbb.putLong(10); - for (int i = 0; i < 15; i++) - mbb.putLong(-2); - flush = mbb.position(); -// for(int i=0;i<2;i++) -// System.nanoTime(); - } - long time = System.nanoTime() - start; - long count = size / 8 / 16; - System.out.printf("Throughput %.1f M msg/s%n", count * 1e3 / time); - } -} diff --git a/src/test/java/com/google/code/java/core/math/RoundingPerformanceMain.java b/src/test/java/com/google/code/java/core/math/RoundingPerformanceMain.java deleted file mode 100644 index c8621af..0000000 --- a/src/test/java/com/google/code/java/core/math/RoundingPerformanceMain.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.math; - -import java.math.BigDecimal; - -public class RoundingPerformanceMain { - public static void main(String... args) { - longCastPerf(); - mathRoundPerf(); - bidDecimalSetScalePerf(); - } - - private static double longCastPerf() { - double sum = 0; // to avoid micro-optimisation. - final int runs = 160 * 1000 * 1000; // about 1 second. - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - double d = i * 0.01; - sum += roundToTwoPlacesCast(d); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %,d ns for rounding using cast%n", time / runs); - return sum; - } - - private static double mathRoundPerf() { - double sum = 0; // to avoid micro-optimisation. - final int runs = 50 * 1000 * 1000; // about one second. - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - double d = i * 0.01; - sum += roundToTwoPlacesMath(d); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %,d ns for rounding using Math.round%n", time / runs); - return sum; - } - - private static double bidDecimalSetScalePerf() { - double sum = 0; // to avoid micro-optimisation. - final int runs = 1000 * 1000; // about 1 second. - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - double d = i * 0.01; - sum += roundToTwoPlacesBigDecimal(d); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %,d ns for rounding using BigDecimal.setScale%n", time / runs); - return sum; - } - - public static double roundToTwoPlacesCast(double d) { - return ((long) (d < 0 ? d * 100 - 0.5 : d * 100 + 0.5)) / 100.0; - } - - public static double roundToTwoPlacesMath(double d) { - return Math.round(d * 100) / 100.0; - } - - public static double roundToTwoPlacesBigDecimal(double d) { - return new BigDecimal(d).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); - } -} diff --git a/src/test/java/com/google/code/java/core/math/SmallestNumberToRoundToOne.java b/src/test/java/com/google/code/java/core/math/SmallestNumberToRoundToOne.java deleted file mode 100644 index 6d6703d..0000000 --- a/src/test/java/com/google/code/java/core/math/SmallestNumberToRoundToOne.java +++ /dev/null @@ -1,78 +0,0 @@ -package com.google.code.java.core.math; -/* - Copyright 2011 Peter Lawrey - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ -/* -In Java 6 prints -Math.round(0.4999999999999999167332731531132594682276248931884765625000000000000000000000000000000000000000000000) is 0 -Math.round(0.4999999999999999167332731531132594682276248931884765625000000000000000000000000000000000000000000001) is 1 - -In Java 7 prints -Math.round(0.4999999999999999722444243843710864894092082977294921874999999999999999999999999999999999999999999999) is 0 -Math.round(0.4999999999999999722444243843710864894092082977294921875000000000000000000000000000000000000000000000) is 1 - - */ - -import java.math.BigDecimal; -import java.math.RoundingMode; - -public class SmallestNumberToRoundToOne { - - public static final BigDecimal TWO = BigDecimal.valueOf(2); - - public static void main(String... args) { - int digits = 80; - - BigDecimal low = BigDecimal.ZERO; - BigDecimal high = BigDecimal.ONE; - - for (int i = 0; i <= 10 * digits / 3; i++) { - BigDecimal mid = low.add(high).divide(TWO, digits, RoundingMode.HALF_UP); - if (mid.equals(low) || mid.equals(high)) - break; - if (Math.round(Double.parseDouble(mid.toString())) > 0) - high = mid; - else - low = mid; - } - - System.out.println("Math.round(" + low + ") is " + - Math.round(Double.parseDouble(low.toString()))); - System.out.println("Math.round(" + high + ") is " + - Math.round(Double.parseDouble(high.toString()))); - } - - static class TwoWaysToConvertDoubleToBigDecimal { - public static void main(String... args) { - System.out.println("new BigDecimal(0.1)= " + new BigDecimal(0.1)); - System.out.println("BigDecimal.valueOf(0.1)= " + BigDecimal.valueOf(0.1)); - } - } - - static class CalculateRepresentedValuesAndMidPoints { - public static void main(String... args) { - long value = Double.doubleToLongBits(0.5); - final BigDecimal x0 = new BigDecimal(0.5); - System.out.println("Value 0.5 is " + x0); - final BigDecimal x1 = new BigDecimal(Double.longBitsToDouble(value - 1)); - System.out.println("The previous value is " + x1); - final BigDecimal x2 = new BigDecimal(Double.longBitsToDouble(value - 2)); - System.out.println("... and the previous is " + x2); - final BigDecimal two = BigDecimal.valueOf(2); - System.out.println("\nThe mid point between " + x0 + "\n\tand " + x1 + "\n\tis " + x0.add(x1).divide(two)); - System.out.println("\n... and the mid point between " + x1 + "\n\tand " + x2 + "\n\tis " + x1.add(x2).divide(two)); - } - } -} diff --git a/src/test/java/com/google/code/java/core/memory/MemoryAlignment.java b/src/test/java/com/google/code/java/core/memory/MemoryAlignment.java deleted file mode 100644 index 6e6fcac..0000000 --- a/src/test/java/com/google/code/java/core/memory/MemoryAlignment.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.memory; - -import java.lang.reflect.Field; -import java.nio.Buffer; -import java.nio.ByteBuffer; - -public class MemoryAlignment { - public static void main(String... args) throws NoSuchFieldException, IllegalAccessException { - { - OneInt r0 = new OneInt(); // load the class. - long free1 = freeMemory(); - OneInt r1 = new OneInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with one int reserved " + (free1 - free2) + " bytes."); - } - { - TwoInt r0 = new TwoInt(); // load the class. - long free1 = freeMemory(); - TwoInt r1 = new TwoInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with two int reserved " + (free1 - free2) + " bytes."); - } - { - ThreeInt r0 = new ThreeInt(); // load the class. - long free1 = freeMemory(); - ThreeInt r1 = new ThreeInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with three int reserved " + (free1 - free2) + " bytes."); - } - { - FourInt r0 = new FourInt(); // load the class. - long free1 = freeMemory(); - FourInt r1 = new FourInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with four int reserved " + (free1 - free2) + " bytes."); - } - { - FiveInt r0 = new FiveInt(); // load the class. - long free1 = freeMemory(); - FiveInt r1 = new FiveInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with five int reserved " + (free1 - free2) + " bytes."); - } - { - SixInt r0 = new SixInt(); // load the class. - long free1 = freeMemory(); - SixInt r1 = new SixInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with six int reserved " + (free1 - free2) + " bytes."); - } - { - SevenInt r0 = new SevenInt(); // load the class. - long free1 = freeMemory(); - SevenInt r1 = new SevenInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with seven int reserved " + (free1 - free2) + " bytes."); - } - { - EightInt r0 = new EightInt(); // load the class. - long free1 = freeMemory(); - EightInt r1 = new EightInt(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with eight int reserved " + (free1 - free2) + " bytes."); - } - - { - OneRef r0 = new OneRef(); // load the class. - long free1 = freeMemory(); - OneRef r1 = new OneRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with one ref reserved " + (free1 - free2) + " bytes."); - } - { - TwoRef r0 = new TwoRef(); // load the class. - long free1 = freeMemory(); - TwoRef r1 = new TwoRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with two ref reserved " + (free1 - free2) + " bytes."); - } - { - ThreeRef r0 = new ThreeRef(); // load the class. - long free1 = freeMemory(); - ThreeRef r1 = new ThreeRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with three ref reserved " + (free1 - free2) + " bytes."); - } - { - FourRef r0 = new FourRef(); // load the class. - long free1 = freeMemory(); - FourRef r1 = new FourRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with four ref reserved " + (free1 - free2) + " bytes."); - } - { - FiveRef r0 = new FiveRef(); // load the class. - long free1 = freeMemory(); - FiveRef r1 = new FiveRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with five ref reserved " + (free1 - free2) + " bytes."); - } - { - SixRef r0 = new SixRef(); // load the class. - long free1 = freeMemory(); - SixRef r1 = new SixRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with six ref reserved " + (free1 - free2) + " bytes."); - } - { - SevenRef r0 = new SevenRef(); // load the class. - long free1 = freeMemory(); - SevenRef r1 = new SevenRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with seven ref reserved " + (free1 - free2) + " bytes."); - } - { - EightRef r0 = new EightRef(); // load the class. - long free1 = freeMemory(); - EightRef r1 = new EightRef(); - long free2 = freeMemory(); - if (free2 == free1) throw new Error("You must run this with -XX:-UseTLAB."); - System.out.println("Class with eight ref reserved " + (free1 - free2) + " bytes."); - } - for (int i = 0; i <= 64; i++) - for (int n = 0; n < 3; n++) { - Field address = Buffer.class.getDeclaredField("address"); - address.setAccessible(true); - ByteBuffer bb1 = ByteBuffer.allocateDirect(i); - ByteBuffer bb2 = ByteBuffer.allocateDirect(i); - long address1 = (Long) address.get(bb1); - long address2 = (Long) address.get(bb2); - System.out.println("Allocating " + i + " bytes of direct memory reserves " + (address2 - address1) + " bytes"); - } - - } - - public static long freeMemory() { - return Runtime.getRuntime().freeMemory(); - } -} - -class OneInt { - int i; -} - -class TwoInt { - int i, j; -} - -class ThreeInt { - int i, j, k; -} - -class FourInt { - int i, j, k, l; -} - -class FiveInt { - int i, j, k, l, m; -} - -class SixInt { - int i, j, k, l, m, n; -} - -class SevenInt { - int i, j, k, l, m, n, o; -} - -class EightInt { - int i, j, k, l, m, n, o, p; -} - -class OneRef { - Object i; -} - -class TwoRef { - Object i, j; -} - -class ThreeRef { - Object i, j, k; -} - -class FourRef { - Object i, j, k, l; -} - -class FiveRef { - Object i, j, k, l, m; -} - -class SixRef { - Object i, j, k, l, m, n; -} - -class SevenRef { - Object i, j, k, l, m, n, o; -} - -class EightRef { - Object i, j, k, l, m, n, o, p; -} diff --git a/src/test/java/com/google/code/java/core/methodhandles/MethodHandleMain.java b/src/test/java/com/google/code/java/core/methodhandles/MethodHandleMain.java deleted file mode 100644 index 2a404ee..0000000 --- a/src/test/java/com/google/code/java/core/methodhandles/MethodHandleMain.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.methodhandles; - -import java.lang.invoke.MethodHandle; -import java.lang.reflect.Method; - -import static java.lang.invoke.MethodHandles.*; -import static java.lang.invoke.MethodType.methodType; - -public class MethodHandleMain { - public static void main(String... args) throws Throwable { - directCallTest(); - reflectionTest(); - methodHandleTest(); - } - - private static long methodHandleTest() throws Throwable { - final Lookup lookup = lookup(); - MethodHandle multiply = lookup.findStatic(MethodHandleMain.class, "multiply", methodType(int.class, int.class, int.class)); - MethodHandle quadruple = insertArguments(multiply, 1, 4); - - System.out.println(multiply.invoke(3, 2)); // prints 6 - System.out.println(quadruple.invoke(5)); // prints 20 - - MethodHandle subtract = lookup.findStatic(MethodHandleMain.class, "subtract", methodType(int.class, int.class, int.class)); - MethodHandle subtractFromFour = insertArguments(subtract, 0, 4); - MethodHandle fourLess = insertArguments(subtract, 1, 4); - System.out.println(subtract.invoke(10, 5)); // prints 5 - System.out.println(subtractFromFour.invoke(10)); // prints -6 - System.out.println(fourLess.invoke(10)); // prints 6 - - long sum = 0; - final int runs = 100000; - long start = System.nanoTime(); - for (int i = 0; i < runs; i += 5) { - sum += (Integer) multiply.invoke(i, i) + - (Integer) quadruple.invoke(i) + - (Integer) subtract.invoke(i, 1) + - (Integer) subtractFromFour.invoke(i) + - (Integer) fourLess.invoke(i); - } - long time = System.nanoTime() - start; - System.out.printf("Method Handle Average call time was %,d%n", time / runs); - return sum; - } - - private static long reflectionTest() throws Throwable { - Method multiply = MethodHandleMain.class.getDeclaredMethod("multiply", int.class, int.class); - - System.out.println(multiply.invoke(null, 3, 2)); - - Method subtract = MethodHandleMain.class.getDeclaredMethod("subtract", int.class, int.class); - System.out.println(subtract.invoke(null, 10, 5)); - - long sum = 0; - final int runs = 100000; - long start = System.nanoTime(); - for (int i = 0; i < runs; i += 5) { - sum += (Integer) multiply.invoke(null, i, i) + - (Integer) multiply.invoke(null, 4, i) + - (Integer) subtract.invoke(null, i, 1) + - (Integer) subtract.invoke(null, 4, i) + - (Integer) subtract.invoke(null, i, 4); - } - long time = System.nanoTime() - start; - System.out.printf("Method Average call time was %,d%n", time / runs); - return sum; - } - - private static long directCallTest() throws Throwable { - System.out.println(multiply(3, 2)); - - System.out.println(subtract(10, 5)); - - long sum = 0; - final int runs = 100000; - long start = System.nanoTime(); - for (int i = 0; i < runs; i += 5) { - sum += multiply(i, i) + - multiply(4, i) + - subtract(i, 1) + - subtract(4, i) + - subtract(i, 4); - } - long time = System.nanoTime() - start; - System.out.printf("Direct call Average call time was %,d%n", time / runs); - return sum; - } - - public static int multiply(int i, int j) { - return i * j; - } - - public static int subtract(int i, int j) { - return i - j; - } -} diff --git a/src/test/java/com/google/code/java/core/parser/ByteBufferFixedWriterTest.java b/src/test/java/com/google/code/java/core/parser/ByteBufferFixedWriterTest.java deleted file mode 100644 index a3fc939..0000000 --- a/src/test/java/com/google/code/java/core/parser/ByteBufferFixedWriterTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import org.junit.Test; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.nio.ByteBuffer; - -import static junit.framework.Assert.assertEquals; - -public class ByteBufferFixedWriterTest { - @Test - public void testWrite() { - doTest(0.9375); - doTest(75116.075116); -/* - doTest(0.9); - doTest(0.1); -*/ - - doTest(0.0); - doTest(1.0); -// doTest(Double.POSITIVE_INFINITY); -// doTest(Double.NaN); - for (double d = Long.MAX_VALUE * 2.0; d > 1; d -= d / 16) - doTest(d); - - for (long d = (long) 1e9; d > 1; d -= d / 16 + 1) - doTest(d / 1e9); - - // powers of 10 - for (double t = 10; t < 1e9; t *= 10) { - doTest(1 / t); - doTest(1 - 1 / t); - } - } - - private void doTest(double v) { - ByteBuffer buffer = ByteBuffer.allocate(128); - ByteBufferFixedWriter writer = new ByteBufferFixedWriter(buffer, 9); - writer.write(v); - writer.close(); - final String text = new String(buffer.array(), 0, buffer.position()); - System.out.print(text); - - BufferedReader br = new BufferedReader(new StringReader(text)); - PrintDoubleReader reader = new PrintDoubleReader(br); - try { - double v2 = reader.read(); - if (v2 == v) return; - - ByteBuffer buffer2 = ByteBuffer.allocate(128); - ByteBufferFixedWriter writer2 = new ByteBufferFixedWriter(buffer2, 9); - writer2.write(v); - writer2.close(); - - assertEquals(v, v2); - } catch (NumberFormatException nfe) { - ByteBuffer buffer2 = ByteBuffer.allocate(128); - ByteBufferFixedWriter writer2 = new ByteBufferFixedWriter(buffer2, 9); - writer2.write(v); - writer2.close(); - - final AssertionError ae = new AssertionError("Unable to read number for " + v); - ae.initCause(nfe); - throw ae; - } catch (IOException e) { - throw new AssertionError(e); - } - } -} diff --git a/src/test/java/com/google/code/java/core/parser/ByteBufferTextDoubleWriterTest.java b/src/test/java/com/google/code/java/core/parser/ByteBufferTextDoubleWriterTest.java deleted file mode 100644 index a813ec4..0000000 --- a/src/test/java/com/google/code/java/core/parser/ByteBufferTextDoubleWriterTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - - -import org.junit.Test; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.nio.ByteBuffer; - -import static junit.framework.Assert.assertEquals; - -public class ByteBufferTextDoubleWriterTest { - @Test - public void testWrite() { - doTest(75116.075116); -/* - doTest(0.9); - doTest(0.1); -*/ - - doTest(0.0); - doTest(1.0); -// doTest(Double.POSITIVE_INFINITY); -// doTest(Double.NaN); - for (double d = Long.MAX_VALUE * 2.0; d > 1e-18; d -= d / 16) - doTest(d); - - // powers of 10 - for (double t = 10; t < 1e16; t *= 10) { - doTest(1 / t); - doTest(1 - 1 / t); - } - } - - private void doTest(double v) { - ByteBuffer buffer = ByteBuffer.allocate(128); - ByteBufferTextDoubleWriter writer = new ByteBufferTextDoubleWriter(buffer); - writer.write(v); - writer.close(); - final String text = new String(buffer.array(), 0, buffer.position()); - System.out.print(text); - - BufferedReader br = new BufferedReader(new StringReader(text)); - PrintDoubleReader reader = new PrintDoubleReader(br); - try { - double v2 = reader.read(); - assertEquals(v, v2); - } catch (NumberFormatException nfe) { - ByteBuffer buffer2 = ByteBuffer.allocate(128); - ByteBufferTextDoubleWriter writer2 = new ByteBufferTextDoubleWriter(buffer); - writer2.write(v); - writer2.close(); - - final AssertionError ae = new AssertionError("Unable to read number for " + v); - ae.initCause(nfe); - throw ae; - } catch (IOException e) { - throw new AssertionError(e); - } - buffer.flip(); - ByteBufferTextDoubleReader reader2 = new ByteBufferTextDoubleReader(buffer); - double v3 = reader2.read(); - if (v != v3) { - buffer.position(0); - ByteBufferTextDoubleReader reader3 = new ByteBufferTextDoubleReader(buffer); - double v3b = reader3.read(); - assertEquals(v, v3); - } - } -} diff --git a/src/test/java/com/google/code/java/core/parser/InMemoryDoublePerfTest.java b/src/test/java/com/google/code/java/core/parser/InMemoryDoublePerfTest.java deleted file mode 100644 index 06a8353..0000000 --- a/src/test/java/com/google/code/java/core/parser/InMemoryDoublePerfTest.java +++ /dev/null @@ -1,319 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import org.junit.Test; - -import java.io.*; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static junit.framework.Assert.assertEquals; - -public class InMemoryDoublePerfTest { - interface PerfTest { - DoubleReader doubleReader(); - - DoubleWriter doubleWriter(); - - void finish(); - - String toString(); - } - - public void doPerf(PerfTest perfTest) throws IOException, InterruptedException { - int runs = 1001; - long[] times = new long[runs]; - double len = 128 * 1024; - for (int n = 0; n < runs; n++) { - Thread.sleep(1); - long start = System.nanoTime(); - - DoubleWriter lw = perfTest.doubleWriter(); - lw.write(len); - for (double i = 0; i < len; i++) { - lw.write(i * 1000001.0 / 1000000); - } - lw.close(); - - DoubleReader lr = perfTest.doubleReader(); - double len2 = lr.read(); - if (len != len2) - assertEquals(len, len2); - - for (double i = 0; i < len; i++) { - lr.read(); - } - lr.close(); - times[n] = System.nanoTime() - start; - } - perfTest.finish(); - Arrays.sort(times); - System.out.printf(perfTest + ": Typically took %.1f ns to write/read per double.%n", (double) times[runs / 2] / len); - } - - @Test - public void testUnsafePerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - final long address = ParserUtils.UNSAFE.allocateMemory(1024 * 1024); - - @Override - public DoubleWriter doubleWriter() { - return new UnsafeDoubleWriter(address); - } - - @Override - public DoubleReader doubleReader() { - return new UnsafeDoubleReader(address); - } - - @Override - public String toString() { - return "Unsafe binary"; - } - - @Override - public void finish() { - ParserUtils.UNSAFE.freeMemory(address); - } - }); - } - - @Test - public void testByteBufferPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocateDirect(1025 * 1024); - - @Override - public DoubleWriter doubleWriter() { - buffer.clear(); - return new ByteBufferDoubleWriter(buffer); - } - - @Override - public DoubleReader doubleReader() { - buffer.flip(); - return new ByteBufferDoubleReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer binary"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testByteBufferTextDirectPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocateDirect(4 * 1024 * 1024); - - @Override - public DoubleWriter doubleWriter() { - buffer.clear(); - return new ByteBufferTextDoubleWriter(buffer); - } - - @Override - public DoubleReader doubleReader() { - buffer.flip(); - return new ByteBufferTextDoubleReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer direct text"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testByteBufferTextPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocate(4 * 1024 * 1024); - - @Override - public DoubleWriter doubleWriter() { - buffer.clear(); - return new ByteBufferTextDoubleWriter(buffer); - } - - @Override - public DoubleReader doubleReader() { -// System.out.println(new String(buffer.array(), 0, buffer.position())); - buffer.flip(); - return new ByteBufferTextDoubleReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer heap text"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testByteBufferFixedPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocate(2 * 1024 * 1024); - - @Override - public DoubleWriter doubleWriter() { - buffer.clear(); - return new ByteBufferFixedWriter(buffer, 9); - } - - @Override - public DoubleReader doubleReader() { -// System.out.println(new String(buffer.array(), 0, buffer.position())); - buffer.flip(); - return new ByteBufferTextDoubleReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer heap text"; - } - - @Override - public void finish() { - } - }); - } - -/* - @Test - public void testUnsafeTextPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - final double address = ParserUtils.UNSAFE.allocateMemory(1025 * 1024); - - @Override - public DoubleWriter doubleWriter() { - return new UnsafeTextDoubleWriter(address); - } - - @Override - public DoubleReader doubleReader() { - return new UnsafeTextDoubleReader(address); - } - - @Override - public String toString() { - return "Unsafe text"; - } - - @Override - public void finish() { - ParserUtils.UNSAFE.freeMemory(address); - } - }); - } -*/ - - @Test - public void testDataPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteArrayOutputStream baos; - - @Override - public DoubleWriter doubleWriter() { - baos = new ByteArrayOutputStream(); - return new DataDoubleWriter(baos); - } - - @Override - public DoubleReader doubleReader() { - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new DataDoubleReader(bais); - } - - @Override - public String toString() { - return "DataStream binary"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testPrintPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteArrayOutputStream baos; - - @Override - public DoubleWriter doubleWriter() { - baos = new ByteArrayOutputStream(); - return new PrintDoubleWriter(new PrintWriter(new OutputStreamWriter(baos))); - } - - @Override - public DoubleReader doubleReader() { - return new PrintDoubleReader( - new BufferedReader( - new InputStreamReader( - new ByteArrayInputStream(baos.toByteArray())))); - } - - @Override - public String toString() { - return "Print text"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testDecimalFormatPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteArrayOutputStream baos; - - @Override - public DoubleWriter doubleWriter() { - baos = new ByteArrayOutputStream(); - return new DecimalFormatDoubleWriter(new PrintWriter(new OutputStreamWriter(baos))); - } - - @Override - public DoubleReader doubleReader() { - return new DecimalFormatDoubleReader( - new BufferedReader( - new InputStreamReader( - new ByteArrayInputStream(baos.toByteArray())))); - } - - @Override - public String toString() { - return "DecimalFormat text"; - } - - @Override - public void finish() { - } - }); - } -} diff --git a/src/test/java/com/google/code/java/core/parser/InMemoryPerfTest.java b/src/test/java/com/google/code/java/core/parser/InMemoryPerfTest.java deleted file mode 100644 index 88761d1..0000000 --- a/src/test/java/com/google/code/java/core/parser/InMemoryPerfTest.java +++ /dev/null @@ -1,287 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import org.junit.Test; - -import java.io.*; -import java.nio.ByteBuffer; -import java.util.Arrays; - -import static junit.framework.Assert.assertEquals; - -public class InMemoryPerfTest { - interface PerfTest { - LongReader longReader(); - - LongWriter longWriter(); - - void finish(); - - String toString(); - } - - public void doPerf(PerfTest perfTest) throws IOException, InterruptedException { - int runs = 1001; - long[] times = new long[runs]; - long len = 128 * 1024; - for (int n = 0; n < runs; n++) { - Thread.sleep(1); - long start = System.nanoTime(); - - LongWriter lw = perfTest.longWriter(); - lw.write(len); - for (long i = 0; i < len; i++) { - lw.write(i); - } - lw.close(); - - LongReader lr = perfTest.longReader(); - long len2 = lr.read(); - if (len != len2) - assertEquals(len, len2); - - for (long i = 0; i < len; i++) { - lr.read(); - } - lr.close(); - times[n] = System.nanoTime() - start; - } - perfTest.finish(); - Arrays.sort(times); - System.out.printf(perfTest + ": Typically took %.1f ns to write/read per long.%n", (double) times[runs / 2] / len); - } - - @Test - public void testUnsafePerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - final long address = ParserUtils.UNSAFE.allocateMemory(1024 * 1024); - - @Override - public LongWriter longWriter() { - return new UnsafeLongWriter(address); - } - - @Override - public LongReader longReader() { - return new UnsafeLongReader(address); - } - - @Override - public String toString() { - return "Unsafe binary"; - } - - @Override - public void finish() { - ParserUtils.UNSAFE.freeMemory(address); - } - }); - } - - @Test - public void testByteBufferPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocateDirect(1025 * 1024); - - @Override - public LongWriter longWriter() { - buffer.clear(); - return new ByteBufferLongWriter(buffer); - } - - @Override - public LongReader longReader() { - buffer.flip(); - return new ByteBufferLongReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer binary"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testByteBufferTextDirectPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocateDirect(1025 * 1024); - - @Override - public LongWriter longWriter() { - buffer.clear(); - return new ByteBufferTextLongWriter(buffer); - } - - @Override - public LongReader longReader() { - buffer.flip(); - return new ByteBufferTextLongReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer direct text"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testByteBufferTextPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteBuffer buffer = ByteBuffer.allocate(1025 * 1024); - - @Override - public LongWriter longWriter() { - buffer.clear(); - return new ByteBufferTextLongWriter(buffer); - } - - @Override - public LongReader longReader() { - buffer.flip(); - return new ByteBufferTextLongReader(buffer); - } - - @Override - public String toString() { - return "ByteBuffer heap text"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testUnsafeTextPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - final long address = ParserUtils.UNSAFE.allocateMemory(1025 * 1024); - - @Override - public LongWriter longWriter() { - return new UnsafeTextLongWriter(address); - } - - @Override - public LongReader longReader() { - return new UnsafeTextLongReader(address); - } - - @Override - public String toString() { - return "Unsafe text"; - } - - @Override - public void finish() { - ParserUtils.UNSAFE.freeMemory(address); - } - }); - } - - @Test - public void testDataPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteArrayOutputStream baos; - - @Override - public LongWriter longWriter() { - baos = new ByteArrayOutputStream(); - return new DataLongWriter(baos); - } - - @Override - public LongReader longReader() { - ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); - return new DataLongReader(bais); - } - - @Override - public String toString() { - return "DataStream binary"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testPrintPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteArrayOutputStream baos; - - @Override - public LongWriter longWriter() { - baos = new ByteArrayOutputStream(); - return new PrintLongWriter(new PrintWriter(new OutputStreamWriter(baos))); - } - - @Override - public LongReader longReader() { - return new PrintLongReader( - new BufferedReader( - new InputStreamReader( - new ByteArrayInputStream(baos.toByteArray())))); - } - - @Override - public String toString() { - return "Print text"; - } - - @Override - public void finish() { - } - }); - } - - @Test - public void testDecimalFormatPerf() throws IOException, InterruptedException { - doPerf(new PerfTest() { - ByteArrayOutputStream baos; - - @Override - public LongWriter longWriter() { - baos = new ByteArrayOutputStream(); - return new DecimalFormatLongWriter(new PrintWriter(new OutputStreamWriter(baos))); - } - - @Override - public LongReader longReader() { - return new DecimalFormatLongReader( - new BufferedReader( - new InputStreamReader( - new ByteArrayInputStream(baos.toByteArray())))); - } - - @Override - public String toString() { - return "DecimalFormat text"; - } - - @Override - public void finish() { - } - }); - } -} diff --git a/src/test/java/com/google/code/java/core/parser/ParserUtilsTest.java b/src/test/java/com/google/code/java/core/parser/ParserUtilsTest.java deleted file mode 100644 index 7367905..0000000 --- a/src/test/java/com/google/code/java/core/parser/ParserUtilsTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.parser; - -import org.junit.Test; - -import static junit.framework.Assert.assertEquals; - -public class ParserUtilsTest { - @Test - public void testDigits() { - long l = (long) 1e18; - for (int i = 19; i > 0; i--) { - assertEquals(i, ParserUtils.digits(l)); - assertEquals(i - 1, ParserUtils.digits(l - 1)); - l /= 10; - } - } -} diff --git a/src/test/java/com/google/code/java/core/recycling/MarketDataPrice.java b/src/test/java/com/google/code/java/core/recycling/MarketDataPrice.java deleted file mode 100644 index 26d6f03..0000000 --- a/src/test/java/com/google/code/java/core/recycling/MarketDataPrice.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.recycling; - -import java.nio.ByteBuffer; - -public class MarketDataPrice { - final int symbol; - double bestBid; - double bestOffer; - - - public MarketDataPrice(int symbol) { - this.symbol = symbol; - } - - - public void readFrom(ByteBuffer bb) { - // it is assumed the symbol has been read. - bestBid = bb.getDouble(); - bestOffer = bb.getDouble(); - } - - public void writeTo(ByteBuffer bb) { - // is is assumed the symbol will be written by the caller - bb.putDouble(bestBid); - bb.putDouble(bestOffer); - } -} diff --git a/src/test/java/com/google/code/java/core/recycling/MarketDataPriceCollection.java b/src/test/java/com/google/code/java/core/recycling/MarketDataPriceCollection.java deleted file mode 100644 index 14e649a..0000000 --- a/src/test/java/com/google/code/java/core/recycling/MarketDataPriceCollection.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.recycling; - - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.List; - -public class MarketDataPriceCollection { - private final List marketDataPrices = new ArrayList(); - - public MarketDataPriceCollection() { - } - - public MarketDataPrice get(int symbol) { - while (symbol >= marketDataPrices.size()) - marketDataPrices.add(new MarketDataPrice(marketDataPrices.size())); - return marketDataPrices.get(symbol); - } - - public void set(int symbol, MarketDataPrice marketDataPrice) { - while (symbol >= marketDataPrices.size()) marketDataPrices.add(null); - marketDataPrices.set(symbol, marketDataPrice); - } - - public void writeTo(ByteBuffer bb) { - bb.putInt(marketDataPrices.size()); - for (int i = 0; i < marketDataPrices.size(); i++) { - MarketDataPrice mdp = marketDataPrices.get(i); - bb.putInt(mdp.symbol); - mdp.writeTo(bb); - } - } - - public void readFrom(ByteBuffer bb) { - int length = bb.getInt(); - while (marketDataPrices.size() > length) - marketDataPrices.remove(marketDataPrices.size() - 1); // remove last. - for (int i = 0; i < length; i++) { - get(i).readFrom(bb); - } - } - - public static MarketDataPriceCollection loadFrom(ByteBuffer bb) { - MarketDataPriceCollection mdpc = new MarketDataPriceCollection(); - mdpc.readFrom(bb); - return mdpc; - } -} diff --git a/src/test/java/com/google/code/java/core/recycling/MarketDataPriceCollectionTest.java b/src/test/java/com/google/code/java/core/recycling/MarketDataPriceCollectionTest.java deleted file mode 100644 index 75d11c0..0000000 --- a/src/test/java/com/google/code/java/core/recycling/MarketDataPriceCollectionTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.recycling; - -import org.junit.Test; - -import java.nio.ByteBuffer; -import java.util.Arrays; - -public class MarketDataPriceCollectionTest { - - public static final int COPY_SIZE = 2 * 1024; - public static final long[] bytes1 = new long[COPY_SIZE]; - public static final long[] bytes2 = new long[COPY_SIZE]; - - final int prices = 1000; - final int testCount = 1000000; - final int runs = 10; - final int warmup = 10000 / runs; - - @Test - public void testPerf() { - MarketDataPriceCollection mdpc = new MarketDataPriceCollection(); - for (int i = 0; i < prices; i++) { - final MarketDataPrice mdp = mdpc.get(i); - mdp.bestBid = 0.998; - mdp.bestOffer = 1.002; - } - ByteBuffer bb = ByteBuffer.allocateDirect(1024 * 1024); - mdpc.writeTo(bb); - bb.flip(); - StringBuilder results = new StringBuilder(); - - int[] recycleTime = new int[testCount], recycleCache = new int[testCount], newObjectTime = new int[testCount], newObjectCache = new int[testCount]; - final MarketDataPriceCollection recycled = new MarketDataPriceCollection(); - for (int i = -warmup; i < testCount; i++) { - doRecycleDeserialize(bb, i, recycleTime, recycleCache, recycled); -// doNewObjectDeserialize(bb, i, newObjectTime, newObjectCache); - } - Arrays.sort(recycleTime); - Arrays.sort(recycleCache); - Arrays.sort(newObjectTime); - Arrays.sort(newObjectCache); - System.out.println("\npercentile, recycled deserialize,recycle copy latency,new object deserialize,new object copy latency"); - for (int p = 1; p <= 99; p += 2) { - int index = testCount * p / 100; - System.out.printf("%2d%%,%d,%d,%d,%d%n", p, recycleTime[index], recycleCache[index], newObjectTime[index], newObjectCache[index]); - } - System.out.println("\npercentile, recycled deserialize,recycle copy latency,new object deserialize,new object copy latency"); - for (int p = 951; p <= 999; p += 2) { - int index = testCount * p / 1000; - System.out.printf("%4.1f%%,%d,%d,%d,%d%n", p / 10.0, recycleTime[index], recycleCache[index], newObjectTime[index], newObjectCache[index]); - } - System.out.println(results); - } - - private void doRecycleDeserialize(ByteBuffer bb, int count, int[] recycleTime, int[] recycleCache, MarketDataPriceCollection mdpc) { - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - bb.position(0); - mdpc.readFrom(bb); - } - final long mid = System.nanoTime(); - long time = mid - start; - System.arraycopy(bytes1, 0, bytes2, 0, bytes1.length); - long copyTime = System.nanoTime() - mid; - if (count >= 0) { - recycleTime[count] = (int) (time / runs); - recycleCache[count] = (int) copyTime; - } - } - - private void doNewObjectDeserialize(ByteBuffer bb, int count, int[] newObjectTime, int[] newObjectCache) { - MarketDataPriceCollection mdpc = null; - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - bb.position(0); - mdpc = MarketDataPriceCollection.loadFrom(bb); - } - final long mid = System.nanoTime(); - long time = mid - start; - System.arraycopy(bytes1, 0, bytes2, 0, bytes1.length); - long copyTime = System.nanoTime() - mid; - if (count >= 0) { - newObjectTime[count] = (int) (time / runs); - newObjectCache[count] = (int) copyTime; - } - } -} diff --git a/src/test/java/com/google/code/java/core/regex/RegexTestOne.java b/src/test/java/com/google/code/java/core/regex/RegexTestOne.java deleted file mode 100644 index 70456c7..0000000 --- a/src/test/java/com/google/code/java/core/regex/RegexTestOne.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2012. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.regex; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class RegexTestOne { - public static void main(String... args) { - String text = "\n" + - "\n" + - "http://www.linkedin.com/groups/gid-2431604monthly\n" + - "http://www.linkedin.com/groups/gid-2430868monthly\n" + - "http://www.linkedin.com/groups/Wireless-Carrier-Reps-Past-Present-2430807monthly\n" + - "http://www.linkedin.com/groups/gid-2430694monthly\n" + - "http://www.linkedin.com/groups/gid-2430575monthly\n" + - "http://www.linkedin.com/groups/gid-2431452monthly\n" + - "http://www.linkedin.com/groups/gid-2432377monthly\n" + - "http://www.linkedin.com/groups/gid-2428508monthly\n" + - "http://www.linkedin.com/groups/gid-2432379monthly\n" + - "http://www.linkedin.com/groups/gid-2432380monthly\n" + - "http://www.linkedin.com/groups/gid-2432381monthly\n" + - "http://www.linkedin.com/groups/gid-2432383monthly\n" + - "http://www.linkedin.com/groups/gid-2432384monthly\n" + - "\n"; - for (int runs : new int[]{1, 10, 100, 1000, 10000, 100000}) { - long time1 = timeRegexFind(text, "\\s*", runs); - long time2 = timeIndexOfFind(text, runs); - System.out.printf("Performing %,d loops, regex took %.3f us and indexOf took %.3f us on average, ratio=%.1f%n", - runs, time1 / 1e3, time2 / 1e3, (double) time1 / time2); - } - } - - private static long timeRegexFind(String text, String find, int runs) { - Pattern regex = Pattern.compile(find); - int count = 0; - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - count = 0; - Matcher matcher = regex.matcher(text); - while (matcher.find()) count++; - } - long time = System.nanoTime() - start; - // System.out.println("Regex found " + count + " matches, took an average of " + time / runs / 1e3 + " micro-seconds looping "+runs+" times"); - return time / runs; - } - - private static long timeIndexOfFind(String text, int runs) { - int count = 0; - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - count = 0; - int pos = 0; - while ((pos = text.indexOf("", pos)) >= 0) { - pos += "".length(); - while (Character.isWhitespace(text.charAt(pos))) - pos++; - if (text.startsWith("", pos)) { - count++; - pos += "".length(); - } - } - } - long time = System.nanoTime() - start; - // System.out.println("IndexOf found " + count + " matches, took an average of " + time / runs / 1e3 + " micro-seconds looping "+runs+" times"); - return time / runs; - } -} diff --git a/src/test/java/com/google/code/java/core/regex/RegexTestTwo.java b/src/test/java/com/google/code/java/core/regex/RegexTestTwo.java deleted file mode 100644 index 92a67e1..0000000 --- a/src/test/java/com/google/code/java/core/regex/RegexTestTwo.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Copyright (c) 2012. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.regex; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class RegexTestTwo { - public static void main(String... args) { - String text = "name=\"rating_count\" value=\"41\""; - for (int runs : new int[]{1, 10, 100, 1000, 10000, 100000, 100000, 100000}) { - long time1 = timeRegexFind(text, "(?:value=\\x22)([^\\x22]+)", runs); - long time2 = timeIndexOfFind(text, runs); - System.out.printf("Performing %,d loops, regex took %.3f us and indexOf took %.3f us on average, ratio=%.1f%n", - runs, time1 / 1e3, time2 / 1e3, (double) time1 / time2); - } - } - - private static long timeRegexFind(String text, String find, int runs) { - Pattern regex = Pattern.compile(find); - int count = 0; - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - count = 0; - Matcher matcher = regex.matcher(text); - while (matcher.find()) { - String value = matcher.group(1); - assert "41".equals(value); - count++; - } - } - long time = System.nanoTime() - start; - // System.out.println("Regex found " + count + " matches, took an average of " + time / runs / 1e3 + " micro-seconds looping "+runs+" times"); - return time / runs; - } - - private static long timeIndexOfFind(String text, int runs) { - int count = 0; - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - count = 0; - int pos = 0; - while ((pos = text.indexOf("value=\"", pos)) >= 0) { - pos += "value=\"".length(); - int end = text.indexOf('"', pos); - String value = text.substring(pos, end); - assert "41".equals(value); - pos = end + 1; - count++; - } - } - long time = System.nanoTime() - start; -// System.out.println("IndexOf found " + count + " matches, took an average of " + time / runs / 1e3 + " micro-seconds looping "+runs+" times"); - return time / runs; - } -} diff --git a/src/test/java/com/google/code/java/core/service/async/AsyncConsumerTest.java b/src/test/java/com/google/code/java/core/service/async/AsyncConsumerTest.java deleted file mode 100644 index 6c73d4d..0000000 --- a/src/test/java/com/google/code/java/core/service/async/AsyncConsumerTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.async; - -import com.google.code.java.core.service.api.ByteBufferListener; -import org.junit.Test; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicInteger; - -public class AsyncConsumerTest { - @Test - public void testAsyncConsumer() throws InterruptedException { - doAsyncTest(128); - for (int bs = 128; bs <= 1024 * 1024; bs *= 2) - doAsyncTest(bs); - } - - private static void doAsyncTest(int bufferSize) throws InterruptedException { - final int runs = 100000000; - final int[] times = new int[runs]; - final AtomicInteger lastRead = new AtomicInteger(); - ByteBufferListener listener = new ByteBufferListener() { - @Override - public void process(ByteBuffer bb) { - int i = -1; - while (bb.remaining() > 0) { - i = bb.getInt(); - long timeNS = bb.getLong(); - long time = System.nanoTime() - timeNS; - times[i] = (int) time; - } - if (i > 0) - lastRead.set(i); - } - - @Override - public void processOther() { - } - }; - AsyncConsumer ac = new AsyncConsumer("ac", bufferSize, listener); - long start = System.nanoTime(); - for (int i = 0; i < runs; i++) { - final ByteBuffer bb = ac.acquireByteBuffer(4 + 8); - bb.putInt(i); - bb.putLong(System.nanoTime()); - ac.releaseByteBuffer(bb); - } - while (lastRead.get() + 1 < runs) ; - - long time = System.nanoTime() - start; - Arrays.sort(times); - System.out.printf("%,d buffer: Throughput %,d msg/s, ", bufferSize, (long) (runs * 1e9 / time)); - System.out.printf("Latency %.1f / %.1f /%.1f μs for 50 / 99 / 99.99th percentile%n", - times[runs / 2] / 1e3, - times[runs - runs / 100] / 1e3, - times[runs - runs / 10000] / 1e3 - ); - ac.stop(); - Thread.yield(); - } -} diff --git a/src/test/java/com/google/code/java/core/service/async/AsyncSocketClientTest.java b/src/test/java/com/google/code/java/core/service/async/AsyncSocketClientTest.java deleted file mode 100644 index 1dd2a46..0000000 --- a/src/test/java/com/google/code/java/core/service/async/AsyncSocketClientTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.service.async; - -import com.google.code.java.core.service.api.ByteBufferListener; -import com.google.code.java.core.socket.EchoService; -import org.junit.Test; - -import java.io.IOException; -import java.nio.ByteBuffer; - -public class AsyncSocketClientTest { - @Test - public void testSend() throws IOException, InterruptedException { - EchoService es = new EchoService(12345); - - ByteBufferListener listener = new ByteBufferListener() { - @Override - public void process(ByteBuffer bb) { - - } - - @Override - public void processOther() { - } - }; - AsyncSocketClient asc = new AsyncSocketClient("localhost", 12345, 1024, listener); -// asc.readingBuffer(12); - es.stop(); - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/Knucleotide2.java b/src/test/java/com/google/code/java/core/shootout/Knucleotide2.java deleted file mode 100644 index 4806a67..0000000 --- a/src/test/java/com/google/code/java/core/shootout/Knucleotide2.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.*; - -public class Knucleotide2 { - static final byte A = 0; - static final byte T = 1; - static final byte C = 2; - static final byte G = 3; - - public static void main(String... args) throws IOException, InterruptedException, ExecutionException { - long start = System.nanoTime(); - - String filename = "/tmp/fasta.txt"; - if (args.length == 1) - filename = args[0]; - - FileInputStream fis = new FileInputStream(filename); - final ByteBuffer bb = fis.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, fis.getChannel().size()).order(ByteOrder.nativeOrder()); - int nThreads = Runtime.getRuntime().availableProcessors(); - ExecutorService es = Executors.newFixedThreadPool(nThreads); - - int startFrom = findStartOfThree(bb, es, nThreads); - int[] count1s = new int[4]; - int[] count2s = new int[4 * 4]; - List counts = performCounts(bb, es, nThreads, startFrom, count1s, count2s); - - for (Future count : counts) count.get(); - - int sum = 0; - for (int count1 : count1s) sum += count1; - printCounts(count1s, sum, "A T C G"); - printCounts(count2s, sum, "AA AT AC AG TA TT TC TG CA CT CC CG GA GT GC GG"); - - int[] ggtCounts = new int[5]; - bb.position(startFrom); - - performSearches(es, bb, ggtCounts, nThreads); - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - - String[] names = "GGT GGTA GGTATT GGTATTTTAATT GGTATTTTAATTTATAGT".split(" "); - for (int i = 0; i < names.length; i++) - System.out.printf("%-9d %s%n", ggtCounts[i], names[i]); - fis.close(); - - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run%n", time / 1e9); - } - - private static void performSearches(ExecutorService es, ByteBuffer bb, int[] ggtCounts, int nThreads) throws ExecutionException, InterruptedException { - ByteBuffer bb2 = bb.slice().order(ByteOrder.nativeOrder()); - int blockSize = (bb2.limit() + nThreads - 1) / nThreads; - for (int i = 0; i < nThreads; i++) { - int min = i * blockSize; - int max = min + blockSize; - bb2.limit(Math.min(max + 18, bb2.capacity())); - bb2.position(min); - ByteBuffer bb3 = bb2.slice().order(ByteOrder.nativeOrder()); - es.submit(new SearchRunnable(bb3, bb3.limit() - 3, ggtCounts)); - } - } - - private static boolean expect(ByteBuffer bb2, char ch) { - byte b; - b = bb2.get(bb2.position()); - if (b == '\n') { - bb2.get(); - b = bb2.get(bb2.position()); - } - if (b != ch & b != ch + 32) - return true; - bb2.get(); - return false; - } - - enum Tester { - BE_TESTER { - private final int GGT = ('G' << 16) | ('G' << 8) | ('T' << 0); - private final int ggt = ('g' << 16) | ('g' << 8) | ('t' << 0); - private final int GNGT = ('G' << 24) | ('\n' << 16) | ('G' << 8) | ('T' << 0); - private final int GGNT = ('G' << 24) | ('G' << 16) | ('\n' << 8) | ('T' << 0); - private final int gngt = ('g' << 24) | ('\n' << 16) | ('g' << 8) | ('t' << 0); - private final int ggnt = ('g' << 24) | ('g' << 16) | ('\n' << 8) | ('t' << 0); - - public boolean isGGT(int i) { - switch (i >>> 8) { - case GGT: - case ggt: - return true; - default: - return false; - } - } - - public boolean isBrokenGGT(int i) { - switch (i) { - case GNGT: - case GGNT: - case gngt: - case ggnt: - return true; - default: - return false; - } - } - }, - LE_TESTER { - private final int GGT = ('G' << 0) | ('G' << 8) | ('T' << 16); - private final int ggt = ('g' << 0) | ('g' << 8) | ('t' << 16); - private final int GNGT = ('G' << 0) | ('\n' << 8) | ('G' << 16) | ('T' << 24); - private final int GGNT = ('G' << 0) | ('G' << 8) | ('\n' << 16) | ('T' << 24); - private final int gngt = ('g' << 0) | ('\n' << 8) | ('g' << 16) | ('t' << 24); - private final int ggnt = ('g' << 0) | ('g' << 8) | ('\n' << 16) | ('t' << 24); - - public boolean isGGT(int i) { - switch (i & 0xFFFFFF) { - case GGT: - case ggt: - return true; - default: - return false; - } - } - - public boolean isBrokenGGT(int i) { - switch (i) { - case GNGT: - case GGNT: - case gngt: - case ggnt: - return true; - default: - return false; - } - } - }; - - public static Tester instance() { - return ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN ? BE_TESTER : LE_TESTER; - } - - public abstract boolean isGGT(int i); - - public abstract boolean isBrokenGGT(int i); - } - - private static void printCounts(int[] ints, int sum, String names) { - String[] nameArr = names.split(" ", -1); - for (int i = 0; i < ints.length; i++) - System.out.printf("%s : %.3f%n", nameArr[i], 100.0 * ints[i] / sum); - System.out.println(); - } - - private static int findStartOfThree(ByteBuffer bb, ExecutorService es, int nThreads) throws InterruptedException { - final ArrayBlockingQueue startOfThree = new ArrayBlockingQueue(1); - int blockSize = bb.remaining() / nThreads; - for (int i = 0; i < nThreads; i++) { - final int min = i * blockSize; - final int max = min + blockSize; - es.submit(new FindThreeRunnable(bb, startOfThree, min, max)); - } - return startOfThree.take(); - } - - private static List performCounts(ByteBuffer bb, ExecutorService es, int nThreads, int startFrom, int[] count1s, int[] count2s) throws ExecutionException, InterruptedException { - int blockSize = bb.remaining() / nThreads; - List futures = new ArrayList(); - for (int i = 0; i < nThreads; i++) { - final int min = startFrom + i * blockSize; - final int max = min + blockSize; - futures.add(es.submit(new Counters(bb, min, max, count1s, count2s))); - } - return futures; - } - - static class Counters implements Runnable { - private final ByteBuffer bb; - private final int min; - private final int max; - private final int[] count1s; - private final int[] count2s; - - public Counters(ByteBuffer bb, int min, int max, int[] count1s, int[] count2s) { - this.bb = bb; - this.min = min; - this.max = max; - this.count1s = count1s; - this.count2s = count2s; - } - - @Override - public void run() { - int[] count1s = new int[4]; - int[] count2s = new int[5 * 4]; - int max = Math.min(this.max, bb.limit()); - if (min >= max) return; - int value = 0, count = 0; - int prev2 = 16; - for (int i = min; i < max; i++) { - switch (bb.get(i)) { - case 'a': - case 'A': - value = (value << 2) | A; - count1s[A]++; - count2s[prev2 | A]++; - prev2 = A * 4; - break; - case 'g': - case 'G': - value = (value << 2) | G; - count1s[G]++; - count2s[prev2 | G]++; - prev2 = G * 4; - break; - case 't': - case 'T': - value = (value << 2) | T; - count1s[T]++; - count2s[prev2 | T]++; - prev2 = T * 4; - break; - case 'c': - case 'C': - value = (value << 2) | C; - count1s[C]++; - count2s[prev2 | C]++; - prev2 = C * 4; - break; - default: - count--; - break; - } - if (++count == 4) { - value = count = 0; - } - } - synchronized (this.count1s) { - addAll(this.count1s, count1s); - addAll(this.count2s, count2s); - } - } - - } - - static void addAll(int[] to, int[] from) { - for (int i = 0; i < to.length; i++) - to[i] += from[i]; - } - - static class FindThreeRunnable implements Runnable { - static final int THREE_L = ('>' << 24) | ('T' << 16) | ('H' << 8) | ('R' << 0); - static final int THREE_B = ('>' << 0) | ('T' << 8) | ('H' << 16) | ('R' << 24); - - static volatile boolean found = false; - private final ByteBuffer bb; - private final BlockingQueue startOfThree; - private final int min; - private final int max; - - public FindThreeRunnable(ByteBuffer bb, BlockingQueue startOfThree, int min, int max) { - this.bb = bb; - this.startOfThree = startOfThree; - this.min = min; - this.max = max; - } - - @Override - public void run() { - try { - for (int i = min; i < max && !found; i++) { - switch (bb.getInt(i)) { - case THREE_B: - case THREE_L: - i += 6; - while (bb.get(i++) != '\n') ; - startOfThree.add(i); - found = true; - return; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - private static class SearchRunnable implements Runnable { - private final ByteBuffer bb2; - private final int max; - private final int[] ggtCounts; - - public SearchRunnable(ByteBuffer bb2, int max, int[] ggtCounts) { - this.bb2 = bb2; - this.max = max; - this.ggtCounts = ggtCounts; - } - - @Override - public void run() { - int[] ggtCounts = new int[this.ggtCounts.length]; - Tester tester = Tester.instance(); - while (bb2.position() < max) { - int bytes = bb2.getInt(); - if (tester.isGGT(bytes)) { - ggtCounts[0]++; - bb2.position(bb2.position() - 1); - } else if (tester.isBrokenGGT(bytes)) { - ggtCounts[0]++; - } else { - bb2.position(bb2.position() - 3); - continue; - } - if (expect(bb2, 'A')) continue; - ggtCounts[1]++; - - if (expect(bb2, 'T') || expect(bb2, 'T')) continue; - - ggtCounts[2]++; - - if (expect(bb2, 'T')) continue; - else if (expect(bb2, 'T')) continue; - else if (expect(bb2, 'A')) continue; - else if (expect(bb2, 'A')) continue; - else if (expect(bb2, 'T')) continue; - else if (expect(bb2, 'T')) continue; - - ggtCounts[3]++; - - if (expect(bb2, 'T') || expect(bb2, 'A') || - expect(bb2, 'T') || expect(bb2, 'A') || - expect(bb2, 'G') || expect(bb2, 'T')) continue; - - ggtCounts[4]++; - } - synchronized (this.ggtCounts) { - addAll(this.ggtCounts, ggtCounts); - } - } - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/Knucleotide3.java b/src/test/java/com/google/code/java/core/shootout/Knucleotide3.java deleted file mode 100644 index 1d61e3c..0000000 --- a/src/test/java/com/google/code/java/core/shootout/Knucleotide3.java +++ /dev/null @@ -1,282 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Field; -import java.util.*; -import java.util.concurrent.*; - -public class Knucleotide3 implements Runnable { - private static final int A = 0, T = 1, C = 2, G = 3, - AA = 4, AT = 5, AC = 6, AG = 7, - TA = 8, TT = 9, TC = 10, TG = 11, - CA = 12, CT = 13, CC = 14, CG = 15, - GA = 16, GT = 17, GC = 18, GG = 19, - GGT = 20, GGTA = 21, GGTATT = 22, GGTATTTTAATT = 23, GGTATTTTAATTTATAGT = 24, - COUNTS = 25; - private static final int BUFFER_SIZE = 1024 * 1024; - - private final BlockingQueue processQueue; - private final BlockingQueue returnQueue; - private final BlockingQueue resultsQueue; - - public Knucleotide3(BlockingQueue processQueue, - BlockingQueue returnQueue, - BlockingQueue resultsQueue) { - this.processQueue = processQueue; - this.returnQueue = returnQueue; - this.resultsQueue = resultsQueue; - } - - public static void main(String... args) throws IOException, InterruptedException { - long start = System.nanoTime(); - InputStream in = args.length == 0 ? System.in : new FileInputStream(args[0]); -// in.skip(127000000); // too cheeky? - int nThreads = Runtime.getRuntime().availableProcessors() * 2; - BlockingQueue processQueue = new ArrayBlockingQueue(nThreads + 1); - BlockingQueue returnQueue = new ArrayBlockingQueue(nThreads + 1); - BlockingQueue resultsQueue = new PriorityBlockingQueue(); - ExecutorService es = Executors.newFixedThreadPool(nThreads); - final Knucleotide3 kstate = new Knucleotide3(processQueue, returnQueue, resultsQueue); - for (int i = 0; i < nThreads; i++) - es.submit(kstate); - - int count = 0, len; - byte[] overlap = null; - do { - final Task task = returnQueue.take(); - final int maxLen; - if (overlap == null) { - overlap = new byte[54]; - maxLen = task.bytes.length; - len = in.read(task.bytes); - task.len = len - overlap.length; - } else { - System.arraycopy(overlap, 0, task.bytes, 0, overlap.length); - maxLen = task.bytes.length - overlap.length; - len = task.len = in.read(task.bytes, overlap.length, maxLen); - } - if (len == maxLen) { - System.arraycopy(task.bytes, task.bytes.length - overlap.length, overlap, 0, overlap.length); - } else { - if (overlap != null) - task.len += overlap.length; - overlap = null; - } - if (task.len > 0) - task.count = count++; - processQueue.offer(task, 1, TimeUnit.MINUTES); - } while (len > 0); - - // poison pill remaining tasks. - for (int i = 0; i < nThreads; i++) { - final Task task = new Task(); - task.len = 0; - processQueue.offer(task, 1, TimeUnit.MINUTES); - } - - Results results = null; - for (int i = 0; i < count; i++) { - Results results2 = resultsQueue.take(); - while (results2.resultNumber != i) { - resultsQueue.add(results2); - results2 = resultsQueue.take(); - } - assert results2.resultNumber == i; - - if (results2.foundThree) - results = results2; - else if (results != null) - results.add(results2); - } - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - results.report(); - - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run%n", time / 1e9); - } - - @Override - public void run() { - - try { - returnQueue.add(new Task()); - do { - Task t = processQueue.take(); - if (t.len <= 0) break; - Results results = new Results(t.count); - byte prev = 0; - - for (int i = 0; i < t.len; i++) { - switch (t.bytes[i]) { - case '>': - if (t.bytes[i + 1] == 'T' || t.bytes[i + 1] == 'H' || t.bytes[i + 1] == 'R' || t.bytes[i + 1] == 'E' || t.bytes[i + 1] == 'E') { - results.clear(); - results.foundThree = true; - while (t.bytes[++i] != '\n') { - } - } - break; - case 'A': - case 'a': - results.count[A]++; - results.count[A * 4 + 4 + prev]++; - prev = A; - break; - case 'C': - case 'c': - results.count[C]++; - results.count[C * 4 + 4 + prev]++; - prev = C; - break; - case 'T': - case 't': - results.count[T]++; - results.count[T * 4 + 4 + prev]++; - prev = T; - break; - case 'G': - case 'g': - results.count[G]++; - results.count[G * 4 + 4 + prev]++; - if (prev == G) { - scan(results, t.bytes, i + 1); - } - prev = G; - break; - default: - break; - } - } - returnQueue.add(t); - resultsQueue.add(results); - } while (true); - } catch (Exception e) { - e.printStackTrace(); - System.exit(-1); - } - } - - private void scan(Results results, byte[] bytes, int i) { - try { - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - results.count[GGT]++; - if (bytes[i] == '\n') i++; - if (bytes[i++] != 'a') return; - results.count[GGTA]++; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - results.count[GGTATT]++; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - - if (bytes[i] == '\n') i++; - if (bytes[i] != 'a' & bytes[i++] != 'A') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 'a' & bytes[i++] != 'A') return; - - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - - results.count[GGTATTTTAATT]++; - - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - - if (bytes[i] == '\n') i++; - if (bytes[i] != 'a' & bytes[i++] != 'A') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - - if (bytes[i] == '\n') i++; - if (bytes[i] != 'a' & bytes[i++] != 'A') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 'g' & bytes[i++] != 'G') return; - if (bytes[i] == '\n') i++; - if (bytes[i] != 't' & bytes[i++] != 'T') return; - - results.count[GGTATTTTAATTTATAGT]++; - } catch (ArrayIndexOutOfBoundsException ignored) { - } - } - - - static class Task { - final byte[] bytes = new byte[BUFFER_SIZE]; - int len; - int count; - } - - static class Results implements Comparable { - final int resultNumber; - final int[] count = new int[COUNTS]; - boolean foundThree; - - public Results(int resultNumber) { - this.resultNumber = resultNumber; - } - - @Override - public int compareTo(Results o) { - return resultNumber - o.resultNumber; - } - - public void clear() { - Arrays.fill(count, 0); - } - - public void add(Results results) { - for (int i = 0; i < COUNTS; i++) - count[i] += results.count[i]; - } - - static final Field[] fields = Knucleotide3.class.getDeclaredFields(); - - void report() { - report(A, G + 1); - System.out.println(); - report(AA, GG + 1); - System.out.println(); - for (int i = GG + 1; i < COUNTS; i++) { - System.out.printf("%-7d %s%n", count[i], fields[i].getName()); - } - System.out.println(); - } - - private void report(int start, int end) { - List toSort = new ArrayList(); - int sum = 0; - for (int i = start; i < end; i++) { - toSort.add(new int[]{i, count[i]}); - sum += count[i]; - } - Collections.sort(toSort, new Comparator() { - @Override - public int compare(int[] o1, int[] o2) { - return o2[1] - o1[1]; - } - }); - for (int[] line : toSort) { - System.out.printf("%s %.3f%n", fields[line[0]].getName(), 100.0 * line[1] / sum); - } - } - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/fannkuchredux.java b/src/test/java/com/google/code/java/core/shootout/fannkuchredux.java deleted file mode 100644 index 375af91..0000000 --- a/src/test/java/com/google/code/java/core/shootout/fannkuchredux.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; -/* -* The Computer Language Benchmarks Game -* http://shootout.alioth.debian.org/ -* -* Contributed by Oleg Mazurov, June 2010 -* -*/ -// run with: java -server -XX:+TieredCompilation -XX:+AggressiveOpts fannkuchredux 12 - -import java.util.concurrent.atomic.AtomicInteger; - -public final class fannkuchredux implements Runnable { - // private static final int NCHUNKS = 150; - private static final int NCHUNKS = 220; - private static int CHUNKSZ; - private static int NTASKS; - private static int n; - private static int[] Fact; - private static int[] maxFlips; - private static int[] chkSums; - private static AtomicInteger taskId; - - int[] p, pp, count; - - void print() { - for (int i = 0; i < p.length; i++) { - System.out.print(p[i] + 1); - } - System.out.println(); - } - - void firstPermutation(int idx) { - for (int i = 0; i < p.length; ++i) { - p[i] = i; - } - - for (int i = count.length - 1; i > 0; --i) { - int d = idx / Fact[i]; - count[i] = d; - idx = idx % Fact[i]; - - System.arraycopy(p, 0, pp, 0, i + 1); - for (int j = 0; j <= i; ++j) { - p[j] = j + d <= i ? pp[j + d] : pp[j + d - i - 1]; - } - } - } - - boolean nextPermutation() { - int first = p[1]; - p[1] = p[0]; - p[0] = first; - - int i = 1; - while (++count[i] > i) { - count[i++] = 0; - int next = p[0] = p[1]; - for (int j = 1; j < i; ++j) { - p[j] = p[j + 1]; - } - p[i] = first; - first = next; - } - return true; - } - - int countFlips() { - int flips = 1; - int first = p[0]; - if (p[first] != 0) { - System.arraycopy(p, 0, pp, 0, pp.length); - do { - ++flips; - for (int lo = 1, hi = first - 1; lo < hi; ++lo, --hi) { - int t = pp[lo]; - pp[lo] = pp[hi]; - pp[hi] = t; - } - int t = pp[first]; - pp[first] = first; - first = t; - } while (pp[first] != 0); - } - return flips; - } - - void runTask(int task) { - int idxMin = task * CHUNKSZ; - int idxMax = Math.min(Fact[n], idxMin + CHUNKSZ); - - firstPermutation(idxMin); - - int maxflips = 1; - int chksum = 0; - for (int i = idxMin; ; ) { - - if (p[0] != 0) { - int flips = countFlips(); - maxflips = Math.max(maxflips, flips); - chksum += i % 2 == 0 ? flips : -flips; - } - - if (++i == idxMax) { - break; - } - - nextPermutation(); - } - maxFlips[task] = maxflips; - chkSums[task] = chksum; - } - - public void run() { - p = new int[n]; - pp = new int[n]; - count = new int[n]; - - int task; - while ((task = taskId.getAndIncrement()) < NTASKS) { - runTask(task); - } - } - - static void printResult(int n, int res, int chk) { - System.out.println(chk + "\nPfannkuchen(" + n + ") = " + res); - } - - public static void main(String[] args) { - n = args.length > 0 ? Integer.parseInt(args[0]) : 12; - if (n < 0 || n > 12) { // 13! won't fit into int - printResult(n, -1, -1); - return; - } - if (n <= 1) { - printResult(n, 0, 0); - return; - } - - Fact = new int[n + 1]; - Fact[0] = 1; - for (int i = 1; i < Fact.length; ++i) { - Fact[i] = Fact[i - 1] * i; - } - - CHUNKSZ = (Fact[n] + NCHUNKS - 1) / NCHUNKS; - NTASKS = (Fact[n] + CHUNKSZ - 1) / CHUNKSZ; - maxFlips = new int[NTASKS]; - chkSums = new int[NTASKS]; - taskId = new AtomicInteger(0); - - long start = System.nanoTime(); - int nthreads = Runtime.getRuntime().availableProcessors(); - Thread[] threads = new Thread[nthreads]; - for (int i = 0; i < nthreads; ++i) { - threads[i] = new Thread(new fannkuchredux()); - threads[i].start(); - } - for (Thread t : threads) { - try { - t.join(); - } catch (InterruptedException e) { - } - } - - int res = 0; - for (int v : maxFlips) { - res = Math.max(res, v); - } - int chk = 0; - for (int v : chkSums) { - chk += v; - } - - printResult(n, res, chk); - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run%n", time / 1e9); - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/shootout/fasta.java b/src/test/java/com/google/code/java/core/shootout/fasta.java deleted file mode 100644 index da7be2c..0000000 --- a/src/test/java/com/google/code/java/core/shootout/fasta.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; -/* - * The Great Computer Language Shootout - * http://shootout.alioth.debian.org/ - * - * modified by Mehmet D. AKIN - * - */ -// run with: java -server -XX:+TieredCompilation -XX:+AggressiveOpts fasta 25000000 - -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -class fasta { - public static final int IM = 139968; - public static final int IA = 3877; - public static final int IC = 29573; - public static int last = 42; - - public static final int LINE_LENGTH = 60; - - // pseudo-random number generator - public static final double random(double max) { - last = (last * IA + IC) % IM; - return max * last / IM; - } - - // Weighted selection from alphabet - public static String ALU = - "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" - + "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" - + "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" - + "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" - + "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" - + "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" - + "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; - public static byte[] ALUB = ALU.getBytes(); - - public static final frequency[] IUB = new frequency[]{ - new frequency('a', 0.27), - new frequency('c', 0.12), - new frequency('g', 0.12), - new frequency('t', 0.27), - - new frequency('B', 0.02), - new frequency('D', 0.02), - new frequency('H', 0.02), - new frequency('K', 0.02), - new frequency('M', 0.02), - new frequency('N', 0.02), - new frequency('R', 0.02), - new frequency('S', 0.02), - new frequency('V', 0.02), - new frequency('W', 0.02), - new frequency('Y', 0.02)}; - - public static final frequency[] HomoSapiens = new frequency[]{ - new frequency('a', 0.3029549426680d), - new frequency('c', 0.1979883004921d), - new frequency('g', 0.1975473066391d), - new frequency('t', 0.3015094502008d)}; - - public static void makeCumulative(frequency[] a) { - double cp = 0.0; - for (int i = 0; i < a.length; i++) { - cp += a[i].p; - a[i].p = cp; - } - } - - // naive - public final static byte selectRandom(frequency[] a) { - int len = a.length; - double r = random(1.0); - for (int i = 0; i < len; i++) - if (r < a[i].p) - return a[i].c; - return a[len - 1].c; - } - - static int BUFFER_SIZE = 1024; - static int index = 0; - static byte[] bbuffer = new byte[BUFFER_SIZE]; - - static final void makeRandomFasta(String id, String desc, frequency[] a, int n, OutputStream writer) throws IOException { - index = 0; - int m = 0; - String descStr = ">" + id + " " + desc + '\n'; - writer.write(descStr.getBytes()); - while (n > 0) { - if (n < LINE_LENGTH) m = n; - else m = LINE_LENGTH; - if (BUFFER_SIZE - index < m) { - writer.write(bbuffer, 0, index); - index = 0; - } - for (int i = 0; i < m; i++) { - bbuffer[index++] = selectRandom(a); - } - bbuffer[index++] = '\n'; - n -= LINE_LENGTH; - } - if (index != 0) writer.write(bbuffer, 0, index); - } - - static final void makeRepeatFasta(String id, String desc, String alu, int n, OutputStream writer) throws IOException { - index = 0; - int m = 0; - int k = 0; - int kn = ALUB.length; - String descStr = ">" + id + " " + desc + '\n'; - writer.write(descStr.getBytes()); - while (n > 0) { - if (n < LINE_LENGTH) m = n; - else m = LINE_LENGTH; - if (BUFFER_SIZE - index < m) { - writer.write(bbuffer, 0, index); - index = 0; - } - for (int i = 0; i < m; i++) { - if (k == kn) k = 0; - bbuffer[index++] = ALUB[k]; - k++; - } - bbuffer[index++] = '\n'; - n -= LINE_LENGTH; - } - if (index != 0) writer.write(bbuffer, 0, index); - } - - public static void main(String[] args) throws IOException { - long start = System.nanoTime(); - makeCumulative(HomoSapiens); - makeCumulative(IUB); - int n = 2500000; - if (args.length > 0) - n = Integer.parseInt(args[0]); - OutputStream out = new BufferedOutputStream(new FileOutputStream("/tmp/fasta.txt")); - makeRepeatFasta("ONE", "Homo sapiens alu", ALU, n * 2, out); - makeRandomFasta("TWO", "IUB ambiguity codes", IUB, n * 3, out); - makeRandomFasta("THREE", "Homo sapiens frequency", HomoSapiens, n * 5, out); - out.close(); - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run%n", time / 1e9); - } - - public static class frequency { - public byte c; - public double p; - - public frequency(char c, double p) { - this.c = (byte) c; - this.p = p; - } - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/shootout/fastaredux.java b/src/test/java/com/google/code/java/core/shootout/fastaredux.java deleted file mode 100644 index 1a7d6fa..0000000 --- a/src/test/java/com/google/code/java/core/shootout/fastaredux.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* - * The Computer Language Benchmarks Game - * http://shootout.alioth.debian.org/ - * - * modified by Enotus - * - */ - -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; - -public class fastaredux { - - static final int LINE_LENGTH = 60; - static final int OUT_BUFFER_SIZE = 256 * 1024; - static final int LOOKUP_SIZE = 4 * 1024; - static final double LOOKUP_SCALE = LOOKUP_SIZE - 1; - - static final class Freq { - byte c; - double p; - - Freq(char cc, double pp) { - c = (byte) cc; - p = pp; - } - } - - static final String ALU = - "GGCCGGGCGCGGTGGCTCACGCCTGTAATCCCAGCACTTTGG" - + "GAGGCCGAGGCGGGCGGATCACCTGAGGTCAGGAGTTCGAGA" - + "CCAGCCTGGCCAACATGGTGAAACCCCGTCTCTACTAAAAAT" - + "ACAAAAATTAGCCGGGCGTGGTGGCGCGCGCCTGTAATCCCA" - + "GCTACTCGGGAGGCTGAGGCAGGAGAATCGCTTGAACCCGGG" - + "AGGCGGAGGTTGCAGTGAGCCGAGATCGCGCCACTGCACTCC" - + "AGCCTGGGCGACAGAGCGAGACTCCGTCTCAAAAA"; - static final Freq[] IUB = { - new Freq('a', 0.27), - new Freq('c', 0.12), - new Freq('g', 0.12), - new Freq('t', 0.27), - new Freq('B', 0.02), - new Freq('D', 0.02), - new Freq('H', 0.02), - new Freq('K', 0.02), - new Freq('M', 0.02), - new Freq('N', 0.02), - new Freq('R', 0.02), - new Freq('S', 0.02), - new Freq('V', 0.02), - new Freq('W', 0.02), - new Freq('Y', 0.02)}; - static final Freq[] HomoSapiens = { - new Freq('a', 0.3029549426680), - new Freq('c', 0.1979883004921), - new Freq('g', 0.1975473066391), - new Freq('t', 0.3015094502008)}; - - static void sumAndScale(Freq[] a) { - double p = 0; - for (int i = 0; i < a.length; i++) - a[i].p = (p += a[i].p) * LOOKUP_SCALE; - a[a.length - 1].p = LOOKUP_SCALE; - } - - static final class Random { - - static final int IM = 139968; - static final int IA = 3877; - static final int IC = 29573; - static final double SCALE = LOOKUP_SCALE / IM; - static int last = 42; - - static double next() { - return SCALE * (last = (last * IA + IC) % IM); - } - } - - static final class Out { - - static final byte buf[] = new byte[OUT_BUFFER_SIZE]; - static final int lim = OUT_BUFFER_SIZE - 2 * LINE_LENGTH - 1; - static int ct = 0; - static OutputStream stream; - - static void checkFlush() throws IOException { - if (ct >= lim) { - stream.write(buf, 0, ct); - ct = 0; - } - } - - static void close() throws IOException { - stream.write(buf, 0, ct); - ct = 0; - stream.close(); - } - } - - static final class RandomFasta { - - static final Freq[] lookup = new Freq[LOOKUP_SIZE]; - - static void makeLookup(Freq[] a) { - for (int i = 0, j = 0; i < LOOKUP_SIZE; i++) { - while (a[j].p < i) j++; - lookup[i] = a[j]; - } - } - - static void addLine(int bytes) throws IOException { - Out.checkFlush(); - int lct = Out.ct; - while (lct < Out.ct + bytes) { - double r = Random.next(); - int ai = (int) r; - while (lookup[ai].p < r) ai++; - Out.buf[lct++] = lookup[ai].c; - } - Out.buf[lct++] = (byte) '\n'; - Out.ct = lct; - } - - static void make(String desc, Freq[] a, int n) throws IOException { - makeLookup(a); - - System.arraycopy(desc.getBytes(), 0, Out.buf, Out.ct, desc.length()); - Out.ct += desc.length(); - - while (n > 0) { - int bytes = Math.min(LINE_LENGTH, n); - addLine(bytes); - n -= bytes; - } - } - } - - static final class RepeatFasta { - - static void make(String desc, byte[] alu, int n) throws IOException { - System.arraycopy(desc.getBytes(), 0, Out.buf, Out.ct, desc.length()); - Out.ct += desc.length(); - - byte buf[] = new byte[alu.length + LINE_LENGTH]; - for (int i = 0; i < buf.length; i += alu.length) - System.arraycopy(alu, 0, buf, i, Math.min(alu.length, buf.length - i)); - - int pos = 0; - while (n > 0) { - int bytes = Math.min(LINE_LENGTH, n); - Out.checkFlush(); - System.arraycopy(buf, pos, Out.buf, Out.ct, bytes); - Out.ct += bytes; - Out.buf[Out.ct++] = (byte) '\n'; - pos = (pos + bytes) % alu.length; - n -= bytes; - } - } - } - - - public static void main(String[] args) throws IOException { - int n = 2500000; - if (args.length > 0) - n = Integer.parseInt(args[0]); - - long start = System.nanoTime(); - for (int i = 0; i < 10; i++) { - sumAndScale(IUB); - sumAndScale(HomoSapiens); - - Out.stream = new BufferedOutputStream(new FileOutputStream("/tmp/fastaredux.txt")); - RepeatFasta.make(">ONE Homo sapiens alu\n", ALU.getBytes(), n * 2); - RandomFasta.make(">TWO IUB ambiguity codes\n", IUB, n * 3); - RandomFasta.make(">THREE Homo sapiens frequency\n", HomoSapiens, n * 5); - Out.close(); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.3f seconds to run%n", time / 1e10); - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/knucleotide.java b/src/test/java/com/google/code/java/core/shootout/knucleotide.java deleted file mode 100644 index 0d2e32c..0000000 --- a/src/test/java/com/google/code/java/core/shootout/knucleotide.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - - contributed by Peter Lawrey -*/ - -import java.io.FileInputStream; -import java.lang.management.ManagementFactory; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.FileChannel; -import java.util.*; -import java.util.concurrent.*; - -public class knucleotide { - static final String ATCG = "ATCG"; - static final int A = 0, T = 1, C = 2, G = 3; - static final int LONGEST_SEARCH = 18; - static final long MASK18 = (1L << (2 * LONGEST_SEARCH)) - 1; - - static byte[] values = new byte[256]; static { - Arrays.fill(values, (byte) -1); - values['A'] = values['a'] = A; - values['T'] = values['t'] = T; - values['C'] = values['c'] = C; - values['G'] = values['g'] = G; - } - - private static long encode(String code) { - long l = 0; - for (int i = 0; i < code.length(); i++) - l = (l << 2) | values[code.charAt(i)]; - return l; - } - - static final long GGT = encode("GGT"); - static final long GGTA = encode("GGTA"); - static final long GGTATT = encode("GGTATT"); - static final long GGTATTTTAATT = encode("GGTATTTTAATT"); - static final long GGTATTTTAATTTATAGT = encode("GGTATTTTAATTTATAGT"); - - static int nThreads = 4; //Runtime.getRuntime().availableProcessors(); - - public static void main(String... args) throws Exception { - long start = System.nanoTime(); - FileInputStream in = args.length == 0 ? openStdin() : new FileInputStream(args[0]); - ExecutorService es = Executors.newFixedThreadPool(nThreads - 1); - FileChannel fc = in.getChannel(); - ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); - int startFrom = findStartOfThree(bb, es, nThreads); - bb.position(startFrom); - - int blockSize = (bb.remaining() + nThreads - 1) / nThreads; - for (int i = 0; i < nThreads; i++) { - int min = startFrom + i * blockSize; - int max = min + blockSize; - bb.limit(Math.min(max, bb.capacity())); - bb.position(min - LONGEST_SEARCH); - final ByteBuffer bb3 = bb.slice().order(ByteOrder.nativeOrder()); - final Runnable task = new Runnable() { - @Override - public void run() { - new Results().process(bb3, 0, bb3.limit()); - } - }; - if (i < nThreads - 1) - es.submit(task); - else - task.run(); - } - - in.close(); - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - Results.report(); - long end = System.nanoTime(); - System.out.printf("%nTook %.3f second to count nucleotides%n", (end - start) / 1e9); - } - - private static FileInputStream openStdin() throws Exception { - int processId = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]); - return new FileInputStream("/proc/" + processId + "/fd/0"); - } - - private static int findStartOfThree(ByteBuffer bb, ExecutorService es, int nThreads) throws InterruptedException { - final ArrayBlockingQueue startOfThree = new ArrayBlockingQueue(1); - int blockSize = bb.remaining() / nThreads; - for (int i = 0; i < nThreads; i++) { - final int min = i * blockSize; - final int max = min + blockSize; - es.submit(new FindThreeRunnable(bb, startOfThree, min, max)); - } - return startOfThree.take(); - } - - static class Results { - static final int LEN = 256 * 1024; - static final int KEY_SIZE = 2 * LONGEST_SEARCH; - static final long COUNT_BASE = 1L << KEY_SIZE; - static final long KEY_MASK = COUNT_BASE - 1; - final long[] keyValues = new long[LEN]; - static final Set ALL_RESULTS = new CopyOnWriteArraySet(); - - Results() { - ALL_RESULTS.add(this); - } - - void increment(long id) { - if (!tryIncrement(id, id)) return; - for (int i = 1; i < LEN; i++) - if (!tryIncrement(id, id + i)) return; - throw new AssertionError(id); - } - - private boolean tryIncrement(long id, long id2) { - int hash = (int) ((id2 + (id2 >>> 17)) & (LEN - 1)); - long key = keyValues[hash]; - if (key == 0) { - keyValues[hash] = id | COUNT_BASE; - } else if ((key & KEY_MASK) == id) { - keyValues[hash] += COUNT_BASE; - } else { - return true; - } - return false; - } - - public static void report() { - int[] count1s = new int[4]; - int[] count2s = new int[4 * 4]; - int[] ggtCounts = new int[5]; - for (Results results : ALL_RESULTS) - for (long key1 : results.keyValues) { - if (key1 == 0) continue; - final long key = key1 & KEY_MASK; - final int value = (int) (key1 >>> KEY_SIZE); - - count1s[((int) (key & ((1 << 2 * 1) - 1)))] += value; - count2s[((int) (key & ((1 << 2 * 2) - 1)))] += value; - if ((key & ((1 << 2 * 3) - 1)) == GGT) ggtCounts[0] += value; - if ((key & ((1 << 2 * 4) - 1)) == GGTA) ggtCounts[1] += value; - if ((key & ((1 << 2 * 6) - 1)) == GGTATT) ggtCounts[2] += value; - if ((key & ((1 << 2 * 12) - 1)) == GGTATTTTAATT) ggtCounts[3] += value; - if (key == GGTATTTTAATTTATAGT) ggtCounts[4] += value; - } - long sum = 0; - SortedMap singles = new TreeMap(Collections.reverseOrder()); - for (int i = 0, count1sLength = count1s.length; i < count1sLength; i++) { - sum += count1s[i]; - singles.put(count1s[i], i); - } - for (Map.Entry entry : singles.entrySet()) - System.out.printf("" + ATCG.charAt(entry.getValue()) + " %5.3f%n", 100.0 * entry.getKey() / sum); - System.out.println(); - SortedMap pairs = new TreeMap(Collections.reverseOrder()); - for (int i = 0, count2sLength = count2s.length; i < count2sLength; i++) - pairs.put(count2s[i], i); - for (Map.Entry entry : pairs.entrySet()) - System.out.printf("" + ATCG.charAt(entry.getValue() / 4) + ATCG.charAt(entry.getValue() % 4) + " %5.3f%n", 100.0 * entry.getKey() / sum); - System.out.println(); - String[] names = "GGT GGTA GGTATT GGTATTTTAATT GGTATTTTAATTTATAGT".split(" "); - for (int i = 0; i < ggtCounts.length; i++) - System.out.printf("%-7d %s%n", ggtCounts[i], names[i]); - } - - public void process(ByteBuffer bytes, int start, int end) { - long l = 0; - for (int i = start; i < start + LONGEST_SEARCH; i++) { - int b = values[bytes.get(i)]; - if (b < 0) continue; - l = (l << 2) | b; - } - for (int i = start + LONGEST_SEARCH; i < end; i++) { - int b = values[bytes.get(i)]; - if (b < 0) continue; - l = (l << 2) | b; - increment(l & MASK18); - } - } - } - - static class FindThreeRunnable implements Runnable { - static final int THREE_L = ('>' << 24) | ('T' << 16) | ('H' << 8) | ('R' << 0); - static final int THREE_B = ('>' << 0) | ('T' << 8) | ('H' << 16) | ('R' << 24); - - static volatile boolean found = false; - private final ByteBuffer bb; - private final BlockingQueue startOfThree; - private final int min; - private final int max; - - public FindThreeRunnable(ByteBuffer bb, BlockingQueue startOfThree, int min, int max) { - this.bb = bb; - this.startOfThree = startOfThree; - this.min = min; - this.max = max; - } - - @Override - public void run() { - try { - for (int i = min; i < max && !found; i++) { - switch (bb.getInt(i)) { - case THREE_B: - case THREE_L: - while (bb.get(i++) != '\n') ; - startOfThree.add(i); - found = true; - return; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/knucleotide0.java b/src/test/java/com/google/code/java/core/shootout/knucleotide0.java deleted file mode 100644 index 6de9398..0000000 --- a/src/test/java/com/google/code/java/core/shootout/knucleotide0.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - - contributed by Leonhard Holz - thanks to James McIlree for the fragmentation idea -*/ - -// run with java -server -XX:+TieredCompilation -XX:+AggressiveOpts knucleotide0 0 - -import java.io.FileInputStream; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -public class knucleotide0 { - private static final byte A = 0; - private static final byte T = 1; - private static final byte C = 2; - private static final byte G = 3; - private static final byte BITS_PER_CHAR = 2; - private static final byte CHAR_BIT_MASK = 3; - - private static final int CHUNK_SIZE = 1024 * 1024 * 2; - private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); - - private static void writeFrequencies(SortedSet set, StringBuilder sb) { - int n = 0; - Iterator i; - - i = set.iterator(); - while (i.hasNext()) { - n += i.next().count; - } - - i = set.iterator(); - while (i.hasNext()) { - Fragment fragment = i.next(); - sb.append(fragment.toString()).append(String.format(" %.3f", fragment.count * 100.0f / n)).append("\n"); - } - - sb.append("\n"); - } - - public static void main(String[] args) throws IOException, InterruptedException, ExecutionException { - long start = System.nanoTime(); - boolean inGenom = false; - List encoders = new ArrayList(); - ExecutorService service = Executors.newFixedThreadPool(NUMBER_OF_CORES); - FileInputStream fis = new FileInputStream("/tmp/fasta.txt"); - int read = CHUNK_SIZE, i; - while (read == CHUNK_SIZE) { - i = 0; - byte[] buffer = new byte[CHUNK_SIZE]; - read = fis.read(buffer); - if (!inGenom) { - for (; i < read; i++) - if (buffer[i] == '\n' && i + 6 < buffer.length) { - if (buffer[++i] == '>' && buffer[++i] == 'T' && buffer[++i] == 'H' && buffer[++i] == 'R' && buffer[++i] == 'E' && buffer[++i] == 'E') { - while (buffer[i++] != '\n') ; - inGenom = true; - break; - } - } - } - if (inGenom) { - Encoder encoder = new Encoder(buffer, i, read); - encoders.add(encoder); - service.execute(encoder); - } - } - fis.close(); - - Counter size1 = new Counter(encoders, 1); - service.execute(size1); - Counter size2 = new Counter(encoders, 2); - service.execute(size2); - - String[] fragments = {"GGT", "GGTA", "GGTATT"}; - Counter[] counters = new Counter[fragments.length]; - for (i = 0; i < fragments.length; i++) { - counters[i] = new Counter(encoders, fragments[i].length()); - service.execute(counters[i]); - } - - String[] largeFragments = {"GGTATTTTAATT", "GGTATTTTAATTTATAGT"}; - List[] counterMap = new ArrayList[largeFragments.length]; - for (i = 0; i < largeFragments.length; i++) { - counterMap[i] = new ArrayList(); - for (int j = 0; j < largeFragments[i].length(); j++) { - OffsetCounter counter = new OffsetCounter(encoders, j, largeFragments[i].length()); - counterMap[i].add(counter); - service.execute(counter); - } - } - - service.shutdown(); - - StringBuilder out = new StringBuilder(1024); - writeFrequencies(new TreeSet(size1.get().values()), out); - writeFrequencies(new TreeSet(size2.get().values()), out); - - for (i = 0; i < fragments.length; i++) { - Fragment fragment = new Fragment(fragments[i]); - out.append(counters[i].get().get(fragment).count).append("\t").append(fragments[i]).append("\n"); - } - - for (i = 0; i < largeFragments.length; i++) { - int count = 0; - Fragment fragment = new Fragment(largeFragments[i]); - for (int j = 0; j < largeFragments[i].length(); j++) { - Fragment counter = counterMap[i].get(j).get().get(fragment); - if (counter != null) { - count += counter.count; - } - } - out.append(count).append("\t").append(largeFragments[i]).append("\n"); - } - - System.out.print(out.toString()); - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run%n", time / 1e9); - } - - private static class Encoder implements Runnable { - private byte[] src; - private int start, end; - private volatile boolean done = false; - private List result = new ArrayList(); - - private static final int CHUNK_SIZE = 1024 * 256; - - private Encoder(byte[] src, int start, int end) { - this.src = src; - this.start = start; - this.end = end; - } - - public List get() throws InterruptedException, ExecutionException { - while (!done) Thread.yield(); - return result; - } - - public void run() { - int p = 0; - byte[] encoded = new byte[CHUNK_SIZE]; - - for (int i = start; i < end; i++) { - byte c = src[i]; - switch (c) { - case 'a': - case 'A': - encoded[p++] = A; - break; - case 't': - case 'T': - encoded[p++] = T; - break; - case 'c': - case 'C': - encoded[p++] = C; - break; - case 'g': - case 'G': - encoded[p++] = G; - break; - default: - continue; - } - if (p == encoded.length) { - result.add(encoded); - encoded = new byte[CHUNK_SIZE]; - p = 0; - } - } - - if (p != 0) { - byte[] last = new byte[p]; - System.arraycopy(encoded, 0, last, 0, p); - result.add(last); - } - - done = true; - } - } - - private static class Fragment implements Comparable { - private int count = 1; - private int charsInValue; - private long value; - - public Fragment(int size) { - this.charsInValue = size; - } - - public Fragment(String s) { - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - switch (c) { - case 'A': - value = value << BITS_PER_CHAR | A; - break; - case 'T': - value = value << BITS_PER_CHAR | T; - break; - case 'G': - value = value << BITS_PER_CHAR | G; - break; - case 'C': - value = value << BITS_PER_CHAR | C; - break; - default: - charsInValue--; - } - charsInValue++; - } - } - - @Override - public int hashCode() { - return (int) value; - } - - @Override - public boolean equals(Object o) { - Fragment f = (Fragment) o; - return f.value == value; - } - - public int compareTo(Fragment o) { - return o.count - count; - } - - public String toString() { - long chars = value; - StringBuilder s = new StringBuilder(); - for (int i = 0; i < charsInValue; i++) { - int c = (int) (chars & CHAR_BIT_MASK); - if (c == A) { - s.insert(0, 'A'); - } else if (c == T) { - s.insert(0, 'T'); - } else if (c == G) { - s.insert(0, 'G'); - } else if (c == C) { - s.insert(0, 'C'); - } - chars >>= BITS_PER_CHAR; - } - return s.toString(); - } - } - - private static class Counter implements Runnable { - private int fragmentSize; - private boolean done = false; - private List nucleotides; - private Map fragments = new HashMap(); - - private Counter(List nucleotides, int fragmentSize) { - this.nucleotides = nucleotides; - this.fragmentSize = fragmentSize; - } - - public Map get() throws InterruptedException, ExecutionException { - while (!done) try { - Thread.sleep(100); - } catch (InterruptedException e) { - // ignored - } - return fragments; - } - - public void run() { - long dna = 0, bitmask = 0; - - for (int i = 0; i < fragmentSize; i++) { - bitmask = bitmask << BITS_PER_CHAR | CHAR_BIT_MASK; - } - - try { - - int j = 0; - byte[] buffer = nucleotides.get(0).get().get(0); - - for (; j < fragmentSize - 1; j++) { - dna = dna << BITS_PER_CHAR | buffer[j]; - } - - Fragment fragment = new Fragment(fragmentSize); - Iterator fit = nucleotides.iterator(); - - while (fit.hasNext()) { - Encoder encoder = fit.next(); - Iterator bit = encoder.get().iterator(); - - while (bit.hasNext()) { - buffer = bit.next(); - - for (; j < buffer.length; j++) { - dna = dna << BITS_PER_CHAR | buffer[j]; - fragment.value = dna & bitmask; - Fragment counter = fragments.get(fragment); - - if (counter != null) { - counter.count++; - } else { - fragments.put(fragment, fragment); - fragment = new Fragment(fragmentSize); - } - } - j = 0; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - done = true; - } - } - - private static class OffsetCounter implements Runnable { - private int offset; - private int fragmentSize; - private boolean done = false; - private List nucleotides; - private Map fragments = new HashMap(); - - private OffsetCounter(List nucleotides, int offset, int fragmentSize) { - this.offset = offset; - this.nucleotides = nucleotides; - this.fragmentSize = fragmentSize; - } - - public Map get() throws InterruptedException, ExecutionException { - while (!done) try { - Thread.sleep(100); - } catch (InterruptedException e) { - // ignored - } - return fragments; - } - - public void run() { - long bitmask = 0; - - for (int i = 0; i < fragmentSize; i++) { - bitmask = bitmask << BITS_PER_CHAR | CHAR_BIT_MASK; - } - - try { - - byte[] buffer; - int j = offset; - Fragment fragment = new Fragment(fragmentSize); - Iterator fit = nucleotides.iterator(); - - while (fit.hasNext()) { - Encoder encoder = fit.next(); - Iterator bit = encoder.get().iterator(); - - while (bit.hasNext()) { - buffer = bit.next(); - - for (; j < buffer.length - fragmentSize; j += fragmentSize) { - long dna = 0; - for (int i = 0; i < fragmentSize; i++) { - dna = dna << BITS_PER_CHAR | buffer[j + i]; - } - fragment.value = dna & bitmask; - Fragment counter = fragments.get(fragment); - - if (counter != null) { - counter.count++; - } else { - fragments.put(fragment, fragment); - fragment = new Fragment(fragmentSize); - } - } - j -= buffer.length - fragmentSize; - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - done = true; - } - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/shootout/knucleotideB.java b/src/test/java/com/google/code/java/core/shootout/knucleotideB.java deleted file mode 100644 index 312731b..0000000 --- a/src/test/java/com/google/code/java/core/shootout/knucleotideB.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.lang.management.ManagementFactory; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.util.Arrays; -import java.util.Set; -import java.util.concurrent.*; - -public class knucleotideB { - static final int A = 0, T = 1, C = 2, G = 3; - static final long MASK18 = (1L << (2 * 18)) - 1; - - static byte[] values = new byte[256]; static { - Arrays.fill(values, (byte) -1); - values['A'] = values['a'] = A; - values['T'] = values['t'] = T; - values['C'] = values['c'] = C; - values['G'] = values['g'] = G; - } - - private static long encode(String code) { - long l = 0; - for (int i = 0; i < code.length(); i++) - l = (l << 2) | values[code.charAt(i)]; - return l; - } - - static final long GGT = encode("GGT"); - static final long GGTA = encode("GGTA"); - static final long GGTATT = encode("GGTATT"); - static final long GGTATTTTAATT = encode("GGTATTTTAATT"); - static final long GGTATTTTAATTTATAGT = encode("GGTATTTTAATTTATAGT"); - - static final int BUFFER_REUSE = 32; // bytes. The min is 18-1+1. - static int nThreads = 4; //Runtime.getRuntime().availableProcessors(); - - public static void main(String... args) throws IOException, InterruptedException { - long start = System.nanoTime(); - FileInputStream in = args.length == 0 ? openStdin() : new FileInputStream(args[0]); - final FileChannel fc = in.getChannel(); - ByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); - ExecutorService es = Executors.newFixedThreadPool(nThreads); - searchForThree(bb, es); - int len; - long mid = System.nanoTime(); - -/* - Task task = Task.FREE_LIST.take(); - while ((len = in.read(task.bytes, BUFFER_REUSE, Task.BUFFER_SIZE - BUFFER_REUSE)) > 0) { - System.arraycopy(bufferReuse, 0, task.bytes, 0, BUFFER_REUSE); - task.start = 0; - task.end = len + BUFFER_REUSE; - es.submit(task); - System.arraycopy(task.bytes, len, bufferReuse, 0, BUFFER_REUSE); - task = Task.FREE_LIST.take(); - } -*/ - in.close(); - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - Results.report(); - long end = System.nanoTime(); - System.out.printf("1) Took %.3f second to find THREE from stdin%n", (mid - start) / 1e9); - System.out.printf("2) Took %.3f second to count nucleotides%n", (end - mid) / 1e9); - } - - private static FileInputStream openStdin() throws FileNotFoundException { - int processId = Integer.parseInt(ManagementFactory.getRuntimeMXBean().getName().split("@")[0]); - return new FileInputStream("/proc/" + processId + "/fd/0"); - } - - private static void searchForThree(ByteBuffer bb, ExecutorService es) throws InterruptedException, IOException { - Task task = Task.FREE_LIST.take(); - int i; - OUTER: - for (i = 0; i < bb.limit(); i++) - if (bb.get(i) == '>' && bb.get(i + 1) == 'T' && bb.get(i + 2) == 'H' && bb.get(i + 3) == 'R' && bb.get(i + 4) == 'E' && bb.get(i + 5) == 'E') - break OUTER; - while (bb.get(++i) != '\n') ; - task.start = i - BUFFER_REUSE; - task.end = bb.limit(); - es.submit(task); - } - - static class Task implements Runnable { - static final ArrayBlockingQueue FREE_LIST = new ArrayBlockingQueue(nThreads + 1); - - static { - for (int i = 0; i <= nThreads; i++) FREE_LIST.add(new Task()); - } - - ByteBuffer bytes; - int start, end; - - @Override - public void run() { - assert !FREE_LIST.contains(this); - Results.LOCAL_RESULTS.get().process(bytes, start, end); - FREE_LIST.add(this); - } - } - - static class Results { - static final int LEN = 256 * 1024; - static final int KEY_SIZE = 2 * 18; - static final long COUNT_BASE = 1L << KEY_SIZE; - static final long KEY_MASK = COUNT_BASE - 1; - final long[] keyValues = new long[LEN]; - static final Set ALL_RESULTS = new CopyOnWriteArraySet(); - static final ThreadLocal LOCAL_RESULTS = new ThreadLocal() { - @Override - protected Results initialValue() { - return new Results(); - } - }; - - Results() { - ALL_RESULTS.add(this); - } - - void increment(long id) { - if (!tryIncrement(id, id)) return; - for (int i = 1; i < LEN; i++) - if (!tryIncrement(id, id + i)) return; - throw new AssertionError(id); - } - - private boolean tryIncrement(long id, long id2) { - int hash = (int) ((id2 + (id2 >>> 17)) & (LEN - 1)); - long key = keyValues[hash]; - if (key == 0) { - keyValues[hash] = id | COUNT_BASE; - } else if ((key & KEY_MASK) == id) { - keyValues[hash] += COUNT_BASE; - } else { - return true; - } - return false; - } - - public static void report() { - int[] count1s = new int[4]; - int[] count2s = new int[4 * 4]; - int[] ggtCounts = new int[5]; - for (Results results : ALL_RESULTS) - for (long key1 : results.keyValues) { - if (key1 == 0) continue; - final long key = key1 & KEY_MASK; - final int value = (int) (key1 >>> KEY_SIZE); - - count1s[((int) (key & ((1 << 2 * 1) - 1)))] += value; - count2s[((int) (key & ((1 << 2 * 2) - 1)))] += value; - if ((key & ((1 << 2 * 3) - 1)) == GGT) ggtCounts[0] += value; - if ((key & ((1 << 2 * 4) - 1)) == GGTA) ggtCounts[1] += value; - if ((key & ((1 << 2 * 6) - 1)) == GGTATT) ggtCounts[2] += value; - if ((key & ((1 << 2 * 12) - 1)) == GGTATTTTAATT) ggtCounts[3] += value; - if (key == GGTATTTTAATTTATAGT) ggtCounts[4] += value; - } - for (int i = 0, count1sLength = count1s.length; i < count1sLength; i++) { - System.out.println(i + " : " + count1s[i]); - } - System.out.println(); - for (int i = 0, count2sLength = count2s.length; i < count2sLength; i++) { - System.out.println(i + " : " + count2s[i]); - } - System.out.println(); - for (int i = 0; i < ggtCounts.length; i++) { - System.out.println(i + " : " + ggtCounts[i]); - } - } - - public void process(ByteBuffer bb, int start, int end) { - long l = 0; - for (int i = start; i < start + BUFFER_REUSE; i++) { - int b = values[bb.get(i)]; - if (b < 0) continue; - l = (l << 2) | b; - } - for (int i = start + BUFFER_REUSE; i < end; i++) { - int b = values[bb.get(i)]; - if (b < 0) continue; - l = (l << 2) | b; - increment(l & MASK18); - } - } - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/mandelbrot.java b/src/test/java/com/google/code/java/core/shootout/mandelbrot.java deleted file mode 100644 index 63ce971..0000000 --- a/src/test/java/com/google/code/java/core/shootout/mandelbrot.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* The Computer Language Benchmarks Game - * http://shootout.alioth.debian.org/ - * - * contributed by Stefan Krause - * slightly modified by Chad Whipkey - * parallelized by Colin D Bennett 2008-10-04 - * reduce synchronization cost by The Anh Tran - * optimizations and refactoring by Enotus 2010-11-11 - */ -// run with java -server -XX:+TieredCompilation -XX:+AggressiveOpts mandelbrot 32000 - -import java.io.BufferedOutputStream; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.util.concurrent.atomic.AtomicInteger; - -public final class mandelbrot { - static byte[][] out; - static AtomicInteger yCt; - static double[] Crb; - static double[] Cib; - - static int getByte(int x, int y) { - double Ci = Cib[y]; - int res = 0; - for (int i = 0; i < 8; i += 2) { - double Zr1 = Crb[x + i]; - double Zi1 = Cib[y]; - - double Zr2 = Crb[x + i + 1]; - double Zi2 = Cib[y]; - - int b = 0; - int j = 49; - do { - double nZr1 = Zr1 * Zr1 - Zi1 * Zi1 + Crb[x + i]; - double nZi1 = Zr1 * Zi1 + Zr1 * Zi1 + Cib[y]; - Zr1 = nZr1; - Zi1 = nZi1; - - double nZr2 = Zr2 * Zr2 - Zi2 * Zi2 + Crb[x + i + 1]; - double nZi2 = Zr2 * Zi2 + Zr2 * Zi2 + Cib[y]; - Zr2 = nZr2; - Zi2 = nZi2; - - if (Zr1 * Zr1 + Zi1 * Zi1 > 4) b |= 2; - if (Zr2 * Zr2 + Zi2 * Zi2 > 4) b |= 1; - if (b == 3) break; - } while (--j > 0); - res = (res << 2) + b; - } - return ~res; - } - - static void putLine(int y, byte[] line) { - for (int xb = 0; xb < line.length; xb++) - line[xb] = (byte) getByte(xb * 8, y); - } - - public static void main(String[] args) throws Exception { - int N = 6000; - if (args.length >= 1) N = Integer.parseInt(args[0]); - - long start = System.nanoTime(); - Crb = new double[N + 7]; - Cib = new double[N + 7]; - double invN = 2.0 / N; - for (int i = 0; i < N; i++) { - Cib[i] = i * invN - 1.0; - Crb[i] = i * invN - 1.5; - } - yCt = new AtomicInteger(); - out = new byte[N][(N + 7) / 8]; - - Thread[] pool = new Thread[2 * Runtime.getRuntime().availableProcessors()]; - for (int i = 0; i < pool.length; i++) - pool[i] = new Thread() { - public void run() { - int y; - while ((y = yCt.getAndIncrement()) < out.length) putLine(y, out[y]); - } - }; - for (Thread t : pool) t.start(); - for (Thread t : pool) t.join(); - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run.%n", time / 1e9); - - OutputStream stream = new BufferedOutputStream(new FileOutputStream("/tmp/mandelbrot.out")); - stream.write(("P4\n" + N + " " + N + "\n").getBytes()); - for (int i = 0; i < N; i++) stream.write(out[i]); - stream.close(); - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/meteor.java b/src/test/java/com/google/code/java/core/shootout/meteor.java deleted file mode 100644 index db9e022..0000000 --- a/src/test/java/com/google/code/java/core/shootout/meteor.java +++ /dev/null @@ -1,848 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - transliterated from C++ (Ben St. John) and D (Michael Deardeuff) by Amir K aka Razii -*/ -// run with: java -server -XX:+TieredCompilation -XX:+AggressiveOpts meteor 2098 - -public final class meteor { - static final int X = 0; - static final int Y = 1; - static final int N_DIM = 2; - - static final int EVEN = 0; - static final int ODD = 1; - static final int N_PARITY = 2; - - static final int GOOD = 0; - static final int BAD = 1; - static final int ALWAYS_BAD = 2; - - static final int OPEN = 0; - static final int CLOSED = 1; - static final int N_FIXED = 2; - - static final int MAX_ISLAND_OFFSET = 1024; - static final int N_COL = 5; - static final int N_ROW = 10; - static final int N_CELL = N_COL * N_ROW; - static final int N_PIECE_TYPE = 10; - static final int N_ORIENT = 12; - - -//-- Globals ------------------------- - - static IslandInfo[] g_islandInfo = new IslandInfo[MAX_ISLAND_OFFSET]; - static int g_nIslandInfo = 0; - static OkPieces[][] g_okPieces = new OkPieces[N_ROW][N_COL]; - - static final int g_firstRegion[] = { - 0x00, 0x01, 0x02, 0x03, 0x04, 0x01, 0x06, 0x07, - 0x08, 0x01, 0x02, 0x03, 0x0c, 0x01, 0x0e, 0x0f, - - 0x10, 0x01, 0x02, 0x03, 0x04, 0x01, 0x06, 0x07, - 0x18, 0x01, 0x02, 0x03, 0x1c, 0x01, 0x1e, 0x1f - }; - - static final int g_flip[] = { - 0x00, 0x10, 0x08, 0x18, 0x04, 0x14, 0x0c, 0x1c, - 0x02, 0x12, 0x0a, 0x1a, 0x06, 0x16, 0x0e, 0x1e, - - 0x01, 0x11, 0x09, 0x19, 0x05, 0x15, 0x0d, 0x1d, - 0x03, 0x13, 0x0b, 0x1b, 0x07, 0x17, 0x0f, 0x1f, - }; - - static final int[] s_firstOne = { - 0, 0, 1, 0, 2, 0, 1, 0, - 3, 0, 1, 0, 2, 0, 1, 0, - - 4, 0, 1, 0, 2, 0, 1, 0, - 3, 0, 1, 0, 2, 0, 1, 0, - }; - - static int getMask(int iPos) { - return (1 << (iPos)); - } - - static int floor(int top, int bot) { - int toZero = top / bot; - // negative numbers should be rounded down, not towards zero; - - if ((toZero * bot != top) && ((top < 0) != (bot <= 0))) - toZero--; - - return toZero; - } - - static int getFirstOne(int v) { - int startPos = 0; - if (v == 0) - return 0; - - int iPos = startPos; - int mask = 0xff << startPos; - while ((mask & v) == 0) { - mask <<= 8; - iPos += 8; - } - int result = (mask & v) >> iPos; - int resultLow = result & 0x0f; - if (resultLow != 0) - iPos += s_firstOne[resultLow]; - else - iPos += 4 + s_firstOne[result >> 4]; - - return iPos; - } - - static int countOnes(int v) { - int n = 0; - while (v != 0) { - n++; - v = v & (v - 1); - } - - return n; - } - - - static int flipTwoRows(int bits) { - int flipped = g_flip[bits >> N_COL] << N_COL; - return (flipped | g_flip[bits & Board.TOP_ROW]); - } - - static void markBad(IslandInfo info, int mask, int eo, boolean always) { - info.hasBad[eo][OPEN] |= mask; - info.hasBad[eo][CLOSED] |= mask; - - if (always) - info.alwaysBad[eo] |= mask; - } - - static void initGlobals() { - for (int i = 0; i < MAX_ISLAND_OFFSET; i++) { - g_islandInfo[i] = new IslandInfo(); - } - - for (int i = 0; i < N_ROW; i++) { - for (int j = 0; j < N_COL; j++) - g_okPieces[i][j] = new OkPieces(); - } - } - - -//-- Classes -------------------------; - - - static class OkPieces { - byte[] nPieces = new byte[N_PIECE_TYPE]; - int[][] pieceVec = new int[N_PIECE_TYPE][N_ORIENT]; - } - - - static class IslandInfo { - int[][] hasBad = new int[N_FIXED][N_PARITY]; - int[][] isKnown = new int[N_FIXED][N_PARITY]; - int[] alwaysBad = new int[N_PARITY]; - } - - - static class Soln { - static final int NO_PIECE = -1; - - boolean isEmpty() { - return (m_nPiece == 0); - } - - void popPiece() { - m_nPiece--; - m_synched = false; - } - - void pushPiece(int vec, int iPiece, int row) { - SPiece p = m_pieces[m_nPiece++]; - p.vec = vec; - p.iPiece = (short) iPiece; - p.row = (short) row; - } - - Soln() { - m_synched = false; - m_nPiece = 0; - init(); - } - - class SPiece { - int vec; - short iPiece; - short row; - - SPiece() { - } - - SPiece(int avec, int apiece, int arow) { - vec = avec; - iPiece = (short) apiece; - row = (short) arow; - } - - SPiece(SPiece other) { - vec = other.vec; - iPiece = other.iPiece; - row = other.row; - } - } - - SPiece[] m_pieces = new SPiece[N_PIECE_TYPE]; - int m_nPiece; - byte[][] m_cells = new byte[N_ROW][N_COL]; - boolean m_synched; - - void init() { - for (int i = 0; i < N_PIECE_TYPE; i++) - m_pieces[i] = new SPiece(); - } - - Soln(int fillVal) { - init(); - m_nPiece = 0; - fill(fillVal); - } - - public Soln clone2() { - Soln s = new Soln(); - for (int i = 0; i < m_pieces.length; i++) - s.m_pieces[i] = new SPiece(m_pieces[i]); - - s.m_nPiece = m_nPiece; - //System.arraycopy(m_cells, 0, s.m_cells, 0, N_CELL); - - for (int i = 0; i < N_ROW; i++) { - for (int j = 0; j < N_COL; j++) { - s.m_cells[i][j] = m_cells[i][j]; - } - } - - s.m_synched = m_synched; - return s; - } - - void fill(int val) { - m_synched = false; - for (int i = 0; i < N_ROW; i++) { - for (int j = 0; j < N_COL; j++) - m_cells[i][j] = (byte) val; - } - } - - public String toString() { - StringBuffer result = new StringBuffer(N_CELL * 2); - - for (int y = 0; y < N_ROW; y++) { - for (int x = 0; x < N_COL; x++) { - int val = m_cells[y][x]; - //if (val == NO_PIECE) result.append('.'); - - { - result.append(val); - } - result.append(' '); - } - result.append('\n'); - - // indent every second line - - if (y % 2 == 0) - result.append(" "); - } - return result.toString(); - } - - void setCells() { - if (m_synched) - return; - - for (int iPiece = 0; iPiece < m_nPiece; iPiece++) { - SPiece p = m_pieces[iPiece]; - int vec = p.vec; - byte pID = (byte) p.iPiece; - int rowOffset = p.row; - - int nNewCells = 0; - for (int y = rowOffset; y < N_ROW; y++) { - for (int x = 0; x < N_COL; x++) { - if ((vec & 1) != 0) { - m_cells[y][x] = pID; - nNewCells++; - } - vec >>= 1; - } - if (nNewCells == Piece.N_ELEM) - break; - } - } - m_synched = true; - } - - boolean lessThan(Soln r) { - if (m_pieces[0].iPiece != r.m_pieces[0].iPiece) { - return m_pieces[0].iPiece < r.m_pieces[0].iPiece; - } - - setCells(); - r.setCells(); - - for (int y = 0; y < N_ROW; y++) { - for (int x = 0; x < N_COL; x++) { - int lval = m_cells[y][x]; - int rval = r.m_cells[y][x]; - - if (lval != rval) - return (lval < rval); - } - } - - return false; - } - - void spin(Soln spun) { - setCells(); - - for (int y = 0; y < N_ROW; y++) { - for (int x = 0; x < N_COL; x++) { - byte flipped = m_cells[N_ROW - y - 1][N_COL - x - 1]; - spun.m_cells[y][x] = flipped; - } - } - - - spun.m_pieces[0].iPiece = m_pieces[N_PIECE_TYPE - 1].iPiece; - spun.m_synched = true; - } - } - - -//----------------------- - - static class Board { - static final int L_EDGE_MASK = - ((1 << 0) | (1 << 5) | (1 << 10) | (1 << 15) | - (1 << 20) | (1 << 25) | (1 << 30)); - static final int R_EDGE_MASK = L_EDGE_MASK << 4; - static final int TOP_ROW = (1 << N_COL) - 1; - static final int ROW_0_MASK = - TOP_ROW | (TOP_ROW << 10) | (TOP_ROW << 20) | (TOP_ROW << 30); - static final int ROW_1_MASK = ROW_0_MASK << 5; - static final int BOARD_MASK = (1 << 30) - 1; - - static int getIndex(int x, int y) { - return y * N_COL + x; - } - - Soln m_curSoln; - Soln m_minSoln; - Soln m_maxSoln; - int m_nSoln; - - Board() { - m_curSoln = new Soln(Soln.NO_PIECE); - m_minSoln = new Soln(N_PIECE_TYPE); - m_maxSoln = new Soln(Soln.NO_PIECE); - m_nSoln = (0); - } - - static boolean badRegion(int[] toFill, int rNew) { - // grow empty region, until it doesn't change any more; - - int region; - do { - region = rNew; - - // simple grow up/down - - rNew |= (region >> N_COL); - rNew |= (region << N_COL); - - // grow right/left - - rNew |= (region & ~L_EDGE_MASK) >> 1; - rNew |= (region & ~R_EDGE_MASK) << 1; - - // tricky growth - - int evenRegion = region & (ROW_0_MASK & ~L_EDGE_MASK); - rNew |= evenRegion >> (N_COL + 1); - rNew |= evenRegion << (N_COL - 1); - int oddRegion = region & (ROW_1_MASK & ~R_EDGE_MASK); - rNew |= oddRegion >> (N_COL - 1); - rNew |= oddRegion << (N_COL + 1); - - // clamp against existing pieces - - rNew &= toFill[0]; - } - while ((rNew != toFill[0]) && (rNew != region)); - - // subtract empty region from board - - toFill[0] ^= rNew; - - int nCells = countOnes(toFill[0]); - return (nCells % Piece.N_ELEM != 0); - } - - static int hasBadIslands(int boardVec, int row) { - // skip over any filled rows - - while ((boardVec & TOP_ROW) == TOP_ROW) { - boardVec >>= N_COL; - row++; - } - - int iInfo = boardVec & ((1 << 2 * N_COL) - 1); - IslandInfo info = g_islandInfo[iInfo]; - - int lastRow = (boardVec >> (2 * N_COL)) & TOP_ROW; - int mask = getMask(lastRow); - int isOdd = row & 1; - - if ((info.alwaysBad[isOdd] & mask) != 0) - return BAD; - - if ((boardVec & (TOP_ROW << N_COL * 3)) != 0) - return calcBadIslands(boardVec, row); - - int isClosed = (row > 6) ? 1 : 0; - - if ((info.isKnown[isOdd][isClosed] & mask) != 0) - return (info.hasBad[isOdd][isClosed] & mask); - - if (boardVec == 0) - return GOOD; - - int hasBad = calcBadIslands(boardVec, row); - - info.isKnown[isOdd][isClosed] |= mask; - if (hasBad != 0) - info.hasBad[isOdd][isClosed] |= mask; - - return hasBad; - } - - static int calcBadIslands(int boardVec, int row) { - int[] toFill = {~boardVec}; - if ((row & 1) != 0) { - row--; - toFill[0] <<= N_COL; - } - - int boardMask = BOARD_MASK; - if (row > 4) { - int boardMaskShift = (row - 4) * N_COL; - boardMask >>= boardMaskShift; - } - toFill[0] &= boardMask; - - // a little pre-work to speed things up - - int bottom = (TOP_ROW << (5 * N_COL)); - boolean filled = ((bottom & toFill[0]) == bottom); - while ((bottom & toFill[0]) == bottom) { - toFill[0] ^= bottom; - bottom >>= N_COL; - } - - int startRegion; - if (filled || (row < 4)) - startRegion = bottom & toFill[0]; - else { - startRegion = g_firstRegion[toFill[0] & TOP_ROW]; - if (startRegion == 0) { - startRegion = (toFill[0] >> N_COL) & TOP_ROW; - startRegion = g_firstRegion[startRegion]; - startRegion <<= N_COL; - } - startRegion |= (startRegion << N_COL) & toFill[0]; - } - - while (toFill[0] != 0) { - if (badRegion(toFill, startRegion)) - return ((toFill[0] != 0) ? ALWAYS_BAD : BAD); - int iPos = getFirstOne(toFill[0]); - startRegion = getMask(iPos); - } - - return GOOD; - } - - static void calcAlwaysBad() { - for (int iWord = 1; iWord < MAX_ISLAND_OFFSET; iWord++) { - IslandInfo isleInfo = g_islandInfo[iWord]; - IslandInfo flipped = g_islandInfo[flipTwoRows(iWord)]; - - for (int i = 0, mask = 1; i < 32; i++, mask <<= 1) { - int boardVec = (i << (2 * N_COL)) | iWord; - if ((isleInfo.isKnown[0][OPEN] & mask) != 0) - continue; - - int hasBad = calcBadIslands(boardVec, 0); - if (hasBad != GOOD) { - boolean always = (hasBad == ALWAYS_BAD); - markBad(isleInfo, mask, EVEN, always); - - int flipMask = getMask(g_flip[i]); - markBad(flipped, flipMask, ODD, always); - } - } - flipped.isKnown[1][OPEN] = -1; - isleInfo.isKnown[0][OPEN] = -1; - } - } - - static boolean hasBadIslandsSingle(int boardVec, int row) { - int[] toFill = {~boardVec}; - boolean isOdd = ((row & 1) != 0); - if (isOdd) { - row--; - toFill[0] <<= N_COL; // shift to even aligned - - toFill[0] |= TOP_ROW; - } - - int startRegion = TOP_ROW; - int lastRow = TOP_ROW << (5 * N_COL); - int boardMask = BOARD_MASK; // all but the first two bits - - if (row >= 4) - boardMask >>= ((row - 4) * N_COL); - else if (isOdd || (row == 0)) - startRegion = lastRow; - - toFill[0] &= boardMask; - startRegion &= toFill[0]; - - while (toFill[0] != 0) { - if (badRegion(toFill, startRegion)) - return true; - int iPos = getFirstOne(toFill[0]); - startRegion = getMask(iPos); - } - - return false; - } - - void genAllSolutions(int boardVec, int placedPieces, int row) { - while ((boardVec & TOP_ROW) == TOP_ROW) { - boardVec >>= N_COL; - row++; - } - int iNextFill = s_firstOne[~boardVec & TOP_ROW]; - OkPieces allowed = g_okPieces[row][iNextFill]; - - int iPiece = getFirstOne(~placedPieces); - int pieceMask = getMask(iPiece); - for (; iPiece < N_PIECE_TYPE; iPiece++, pieceMask <<= 1) { - if ((pieceMask & placedPieces) != 0) - continue; - - placedPieces |= pieceMask; - for (int iOrient = 0; iOrient < allowed.nPieces[iPiece]; iOrient++) { - int pieceVec = allowed.pieceVec[iPiece][iOrient]; - - if ((pieceVec & boardVec) != 0) - continue; - - boardVec |= pieceVec; - - if ((hasBadIslands(boardVec, row)) != 0) { - boardVec ^= pieceVec; - continue; - } - - m_curSoln.pushPiece(pieceVec, iPiece, row); - - // recur or record solution - - if (placedPieces != Piece.ALL_PIECE_MASK) - genAllSolutions(boardVec, placedPieces, row); - else - recordSolution(m_curSoln); - - boardVec ^= pieceVec; - m_curSoln.popPiece(); - } - - placedPieces ^= pieceMask; - } - } - - void recordSolution(Soln s) { - m_nSoln += 2; - - if (m_minSoln.isEmpty()) { - m_minSoln = m_maxSoln = s.clone2(); - return; - } - - if (s.lessThan(m_minSoln)) - m_minSoln = s.clone2(); - else if (m_maxSoln.lessThan(s)) - m_maxSoln = s.clone2(); - - Soln spun = new Soln(); - s.spin(spun); - if (spun.lessThan(m_minSoln)) - m_minSoln = spun; - else if (m_maxSoln.lessThan(spun)) - m_maxSoln = spun; - } - } - -//---------------------- - - static class Piece { - class Instance { - long m_allowed; - int m_vec; - int m_offset; - } - - static final int N_ELEM = 5; - static final int ALL_PIECE_MASK = (1 << N_PIECE_TYPE) - 1; - static final int SKIP_PIECE = 5; - - static final int BaseVecs[] = { - 0x10f, 0x0cb, 0x1087, 0x427, 0x465, - 0x0c7, 0x8423, 0x0a7, 0x187, 0x08f - }; - - static Piece[][] s_basePiece = new Piece[N_PIECE_TYPE][N_ORIENT]; - - Instance[] m_instance = new Instance[N_PARITY]; - - void init() { - for (int i = 0; i < N_PARITY; i++) - m_instance[i] = new Instance(); - } - - Piece() { - init(); - } - - static { - for (int i = 0; i < N_PIECE_TYPE; i++) { - for (int j = 0; j < N_ORIENT; j++) - s_basePiece[i][j] = new Piece(); - } - } - - static void setCoordList(int vec, int[][] pts) { - int iPt = 0; - int mask = 1; - for (int y = 0; y < N_ROW; y++) { - for (int x = 0; x < N_COL; x++) { - if ((mask & vec) != 0) { - pts[iPt][X] = x; - pts[iPt][Y] = y; - - iPt++; - } - mask <<= 1; - } - } - } - - static int toBitVector(int[][] pts) { - int y, x; - int result = 0; - for (int iPt = 0; iPt < N_ELEM; iPt++) { - x = pts[iPt][X]; - y = pts[iPt][Y]; - - int pos = Board.getIndex(x, y); - result |= (1 << pos); - } - - return result; - } - - static void shiftUpLines(int[][] pts, int shift) { - - for (int iPt = 0; iPt < N_ELEM; iPt++) { - if ((pts[iPt][Y] & shift & 0x1) != 0) - (pts[iPt][X])++; - pts[iPt][Y] -= shift; - } - } - - static int shiftToX0(int[][] pts, Instance instance, int offsetRow) { - int x, y, iPt; - int xMin = pts[0][X]; - int xMax = xMin; - for (iPt = 1; iPt < N_ELEM; iPt++) { - x = pts[iPt][X]; - y = pts[iPt][Y]; - - if (x < xMin) - xMin = x; - else if (x > xMax) - xMax = x; - } - - int offset = N_ELEM; - for (iPt = 0; iPt < N_ELEM; iPt++) { - - pts[iPt][X] -= xMin; - - if ((pts[iPt][Y] == offsetRow) && (pts[iPt][X] < offset)) - offset = pts[iPt][X]; - } - - instance.m_offset = offset; - instance.m_vec = toBitVector(pts); - return xMax - xMin; - } - - void setOkPos(int isOdd, int w, int h) { - Instance p = m_instance[isOdd]; - p.m_allowed = 0; - long posMask = 1L << (isOdd * N_COL); - - for (int y = isOdd; y < N_ROW - h; y += 2, posMask <<= N_COL) { - if ((p.m_offset) != 0) - posMask <<= p.m_offset; - - for (int xPos = 0; xPos < N_COL - p.m_offset; xPos++, posMask <<= 1) { - - if (xPos >= N_COL - w) - continue; - - int pieceVec = p.m_vec << xPos; - - if (Board.hasBadIslandsSingle(pieceVec, y)) - continue; - - p.m_allowed |= posMask; - } - } - } - - static void genOrientation(int vec, int iOrient, Piece target) { - int[][] pts = new int[N_ELEM][N_DIM]; - setCoordList(vec, pts); - - int y, x, iPt; - int rot = iOrient % 6; - int flip = iOrient >= 6 ? 1 : 0; - if (flip != 0) { - for (iPt = 0; iPt < N_ELEM; iPt++) - pts[iPt][Y] = -pts[iPt][Y]; - } - - while ((rot--) != 0) { - for (iPt = 0; iPt < N_ELEM; iPt++) { - x = pts[iPt][X]; - y = pts[iPt][Y]; - - int xNew = floor((2 * x - 3 * y + 1), 4); - int yNew = floor((2 * x + y + 1), 2); - pts[iPt][X] = xNew; - pts[iPt][Y] = yNew; - } - } - - int yMin = pts[0][Y]; - int yMax = yMin; - for (iPt = 1; iPt < N_ELEM; iPt++) { - y = pts[iPt][Y]; - - if (y < yMin) - yMin = y; - else if (y > yMax) - yMax = y; - } - int h = yMax - yMin; - Instance even = target.m_instance[EVEN]; - Instance odd = target.m_instance[ODD]; - - shiftUpLines(pts, yMin); - int w = shiftToX0(pts, even, 0); - target.setOkPos(EVEN, w, h); - even.m_vec >>= even.m_offset; - - shiftUpLines(pts, -1); - w = shiftToX0(pts, odd, 1); - odd.m_vec >>= N_COL; - target.setOkPos(ODD, w, h); - odd.m_vec >>= odd.m_offset; - } - - static void genAllOrientations() { - for (int iPiece = 0; iPiece < N_PIECE_TYPE; iPiece++) { - int refPiece = BaseVecs[iPiece]; - for (int iOrient = 0; iOrient < N_ORIENT; iOrient++) { - Piece p = s_basePiece[iPiece][iOrient]; - genOrientation(refPiece, iOrient, p); - if ((iPiece == SKIP_PIECE) && (((iOrient / 3) & 1) != 0)) - p.m_instance[0].m_allowed = p.m_instance[1].m_allowed = 0; - } - } - for (int iPiece = 0; iPiece < N_PIECE_TYPE; iPiece++) { - for (int iOrient = 0; iOrient < N_ORIENT; iOrient++) { - long mask = 1; - for (int iRow = 0; iRow < N_ROW; iRow++) { - Instance p = getPiece(iPiece, iOrient, (iRow & 1)); - for (int iCol = 0; iCol < N_COL; iCol++) { - OkPieces allowed = g_okPieces[iRow][iCol]; - if ((p.m_allowed & mask) != 0) { - allowed.pieceVec[iPiece][allowed.nPieces[iPiece]] = p.m_vec << iCol; - (allowed.nPieces[iPiece])++; - } - - mask <<= 1; - } - } - } - } - } - - static Instance getPiece(int iPiece, int iOrient, int iParity) { - return s_basePiece[iPiece][iOrient].m_instance[iParity]; - } - } - - -//-- Main --------------------------- - - public static void main(String[] args) { - if (args.length > 2) - System.exit(-1); // spec says this is an error; - - - Board b = null; - long start = System.nanoTime(); - for (int i = 0; i < 100; i++) { - initGlobals(); - b = new Board(); - Piece.genAllOrientations(); - Board.calcAlwaysBad(); - b.genAllSolutions(0, 0, 0); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.6f seconds to run%n", time / 1e11); - - System.out.println(b.m_nSoln + " solutions found\n"); - System.out.println(b.m_minSoln); - System.out.println(b.m_maxSoln); - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/shootout/nbody.java b/src/test/java/com/google/code/java/core/shootout/nbody.java deleted file mode 100644 index 6044cec..0000000 --- a/src/test/java/com/google/code/java/core/shootout/nbody.java +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* The Computer Language Benchmarks Game - - http://shootout.alioth.debian.org/ - - contributed by Mark C. Lewis - modified slightly by Chad Whipkey -*/ -// run with: java -server -XX:+TieredCompilation -XX:+AggressiveOpts nbody 50000000 - -public final class nbody { - public static void main(String[] args) { - int n = Integer.parseInt(args[0]); - - long start = System.nanoTime(); - NBodySystem bodies = new NBodySystem(); - System.out.printf("%.9f\n", bodies.energy()); - for (int i = 0; i < n; ++i) - bodies.advance(0.01); - System.out.printf("%.9f\n", bodies.energy()); - long time = System.nanoTime() - start; - System.out.printf("Took %.3f seconds to run%n", time / 1e9); - } -} - -final class NBodySystem { - private Body[] bodies; - - public NBodySystem() { - bodies = Body.values(); - - double px = 0.0; - double py = 0.0; - double pz = 0.0; - for (Body body : bodies) { - px += body.vx * body.mass; - py += body.vy * body.mass; - pz += body.vz * body.mass; - } - bodies[0].offsetMomentum(px, py, pz); - } - - public void advance(double dt) { - - for (int i = 0; i < bodies.length; ++i) { - Body iBody = bodies[i]; - for (int j = i + 1; j < bodies.length; ++j) { - final Body body = bodies[j]; - double dx = iBody.x - body.x; - double dy = iBody.y - body.y; - double dz = iBody.z - body.z; - - double dSquared = dx * dx + dy * dy + dz * dz; - double distance = Math.sqrt(dSquared); - double mag = dt / (dSquared * distance); - - iBody.vx -= dx * body.mass * mag; - iBody.vy -= dy * body.mass * mag; - iBody.vz -= dz * body.mass * mag; - - body.vx += dx * iBody.mass * mag; - body.vy += dy * iBody.mass * mag; - body.vz += dz * iBody.mass * mag; - } - } - - for (Body body : bodies) { - body.x += dt * body.vx; - body.y += dt * body.vy; - body.z += dt * body.vz; - } - } - - public double energy() { - double dx, dy, dz, distance; - double e = 0.0; - - for (int i = 0; i < bodies.length; ++i) { - Body iBody = bodies[i]; - e += 0.5 * iBody.mass * - (iBody.vx * iBody.vx - + iBody.vy * iBody.vy - + iBody.vz * iBody.vz); - - for (int j = i + 1; j < bodies.length; ++j) { - Body jBody = bodies[j]; - dx = iBody.x - jBody.x; - dy = iBody.y - jBody.y; - dz = iBody.z - jBody.z; - - distance = Math.sqrt(dx * dx + dy * dy + dz * dz); - e -= (iBody.mass * jBody.mass) / distance; - } - } - return e; - } -} - - -enum Body { - SUN {{ - mass = SOLAR_MASS; - }}, - JUPITER {{ - x = 4.84143144246472090e+00; - y = -1.16032004402742839e+00; - z = -1.03622044471123109e-01; - vx = 1.66007664274403694e-03 * DAYS_PER_YEAR; - vy = 7.69901118419740425e-03 * DAYS_PER_YEAR; - vz = -6.90460016972063023e-05 * DAYS_PER_YEAR; - mass = 9.54791938424326609e-04 * SOLAR_MASS; - }}, - SATURN {{ - x = 8.34336671824457987e+00; - y = 4.12479856412430479e+00; - z = -4.03523417114321381e-01; - vx = -2.76742510726862411e-03 * DAYS_PER_YEAR; - vy = 4.99852801234917238e-03 * DAYS_PER_YEAR; - vz = 2.30417297573763929e-05 * DAYS_PER_YEAR; - mass = 2.85885980666130812e-04 * SOLAR_MASS; - }}, - URANUS {{ - x = 1.28943695621391310e+01; - y = -1.51111514016986312e+01; - z = -2.23307578892655734e-01; - vx = 2.96460137564761618e-03 * DAYS_PER_YEAR; - vy = 2.37847173959480950e-03 * DAYS_PER_YEAR; - vz = -2.96589568540237556e-05 * DAYS_PER_YEAR; - mass = 4.36624404335156298e-05 * SOLAR_MASS; - }}, - NEPTUNE {{ - x = 1.53796971148509165e+01; - y = -2.59193146099879641e+01; - z = 1.79258772950371181e-01; - vx = 2.68067772490389322e-03 * DAYS_PER_YEAR; - vy = 1.62824170038242295e-03 * DAYS_PER_YEAR; - vz = -9.51592254519715870e-05 * DAYS_PER_YEAR; - mass = 5.15138902046611451e-05 * SOLAR_MASS; - }}; - - static final double PI = 3.141592653589793; - static final double SOLAR_MASS = 4 * PI * PI; - // NOTE: there are 365.2425 days in the gregorian calender - static final double DAYS_PER_YEAR = 365.24; - - public double x, y, z, vx, vy, vz, mass; - - Body offsetMomentum(double px, double py, double pz) { - vx = -px / SOLAR_MASS; - vy = -py / SOLAR_MASS; - vz = -pz / SOLAR_MASS; - return this; - } -} diff --git a/src/test/java/com/google/code/java/core/shootout/revcomp.java b/src/test/java/com/google/code/java/core/shootout/revcomp.java deleted file mode 100644 index 21d6f2f..0000000 --- a/src/test/java/com/google/code/java/core/shootout/revcomp.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* The Computer Language Benchmarks Game - http://shootout.alioth.debian.org/ - - contributed by Leonhard Holz - thanks to Anthony Donnefort for the basic mapping idea -*/ -// run with: java -server -XX:+TieredCompilation -XX:+AggressiveOpts revcomp 0 - -import java.io.BufferedOutputStream; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class revcomp { - private static final byte[] map = new byte[256]; - private static final int CHUNK_SIZE = 1024 * 1024; - private static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors(); - private static final ExecutorService service = Executors.newFixedThreadPool(NUMBER_OF_CORES); - private static final List list = new CopyOnWriteArrayList(); - private static BufferedOutputStream out; - - - static { - for (int i = 0; i < map.length; i++) { - map[i] = (byte) i; - } - map['t'] = map['T'] = 'A'; - map['a'] = map['A'] = 'T'; - map['g'] = map['G'] = 'C'; - map['c'] = map['C'] = 'G'; - map['v'] = map['V'] = 'B'; - map['h'] = map['H'] = 'D'; - map['r'] = map['R'] = 'Y'; - map['m'] = map['M'] = 'K'; - map['y'] = map['Y'] = 'R'; - map['k'] = map['K'] = 'M'; - map['b'] = map['B'] = 'V'; - map['d'] = map['D'] = 'H'; - map['u'] = map['U'] = 'A'; - } - - public static void main(String[] args) throws IOException, InterruptedException { - long start = System.nanoTime(); - int read; - byte[] buffer; - Finder lastFinder = null; - FileInputStream fis = new FileInputStream("/tmp/fasta.txt"); - out = new BufferedOutputStream(new FileOutputStream("/tmp/revcomp.txt")); - do { - buffer = new byte[CHUNK_SIZE]; - read = fis.read(buffer); - for (int i = 0; i < 1000; i++) - list.add(buffer); - - Finder finder = new Finder(buffer, read, lastFinder); - service.execute(finder); - lastFinder = finder; - - } while (read == CHUNK_SIZE); - fis.close(); - Status status = lastFinder.finish(); - Mapper mapper = new Mapper(status.lastFinding, status.count - 1, status.lastMapper); - service.execute(mapper); - - service.shutdown(); - service.awaitTermination(1, TimeUnit.MINUTES); - out.close(); - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.6f seconds%n", time / 1e12); - } - - private static final class Status { - private int count = 0; - private int lastFinding = 0; - private Mapper lastMapper = null; - } - - private static final class Finder implements Runnable { - private int size; - private byte[] a; - private Status status; - private Finder previous; - private boolean done = false; - - public Finder(byte[] a, int size, Finder previous) { - this.a = a; - this.size = size; - this.previous = previous; - } - - public Status finish() { - while (!done) try { - Thread.sleep(1); - } catch (InterruptedException e) { - // ignored - } - return status; - } - - public void run() { - LinkedList findings = new LinkedList(); - - for (int i = 0; i < size; i++) { - if (a[i] == '>') { - findings.add(i); - } - } - - if (previous == null) { - status = new Status(); - } else { - status = previous.finish(); - findings.add(0, status.lastFinding); - for (int i = 1; i < findings.size(); i++) { - findings.set(i, findings.get(i) + status.count); - } - } - - if (findings.size() > 1) for (int i = 0; i < findings.size() - 1; i++) { - status.lastMapper = new Mapper(findings.get(i), findings.get(i + 1) - 1, status.lastMapper); - service.execute(status.lastMapper); - } - - status.lastFinding = findings.get(findings.size() - 1); - status.count += size; - done = true; - } - } - - private static final class Mapper implements Runnable { - private int end; - private int start; - private Mapper previous; - private boolean done = false; - - public Mapper(int start, int end, Mapper previous) { - this.end = end; - this.start = start; - this.previous = previous; - } - - public void finish() { - while (!done) try { - Thread.sleep(1); - } catch (InterruptedException e) { - // ignored - } - } - - public void run() { - int[] positions = find(list, start, end); - - int lp1 = positions[0]; - byte[] tob = list.get(lp1); - - int lp2 = positions[2]; - byte[] bot = list.get(lp2); - - int p1 = positions[1]; - while (tob[p1] != '\n') p1++; - - int p2 = positions[3]; - - while (lp1 < lp2 || p1 < p2) { - if (tob[p1] == '\n') { - p1++; - } else if (bot[p2] == '\n') { - p2--; - } else { - byte tmp = tob[p1]; - tob[p1] = map[bot[p2]]; - bot[p2] = map[tmp]; - p1++; - p2--; - } - if (p1 == tob.length) { - lp1++; - tob = list.get(lp1); - p1 = 0; - } - if (p2 == -1) { - lp2--; - bot = list.get(lp2); - p2 = bot.length - 1; - } - } - - if (previous != null) { - previous.finish(); - } - - write(list, positions[0], positions[1], positions[2], positions[3]); - done = true; - } - } - - private static void write(List list, int lpStart, int start, int lpEnd, int end) { - try { - byte[] a = list.get(lpStart); - while (lpStart < lpEnd) { - out.write(a, start, a.length - start); - lpStart++; - a = list.get(lpStart); - start = 0; - } - out.write(a, start, end - start + 1); - } catch (IOException e) { - e.printStackTrace(); - } - } - - private static int[] find(List list, int start, int end) { - int n = 0, lp = 0; - int[] result = new int[4]; - boolean foundStart = false; - - for (byte[] bytes : list) { - if (!foundStart && n + bytes.length > start) { - result[0] = lp; - result[1] = start - n; - foundStart = true; - } - if (foundStart && n + bytes.length > end) { - result[2] = lp; - result[3] = end - n; - break; - } - n += bytes.length; - lp++; - } - return result; - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/shootout/spectralnorm.java b/src/test/java/com/google/code/java/core/shootout/spectralnorm.java deleted file mode 100644 index 5126753..0000000 --- a/src/test/java/com/google/code/java/core/shootout/spectralnorm.java +++ /dev/null @@ -1,163 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.shootout; - -/* -The Computer Language Benchmarks Game -http://shootout.alioth.debian.org/ - -Based on C# entry by Isaac Gouy -contributed by Jarkko Miettinen -Parallel by The Anh Tran - */ -// run with: java -server -XX:+TieredCompilation -XX:+AggressiveOpts spectralnorm 5500 - -import java.text.DecimalFormat; -import java.text.NumberFormat; -import java.util.concurrent.CyclicBarrier; - -public class spectralnorm { - private static final NumberFormat formatter = new DecimalFormat("#.000000000"); - - public static void main(String[] args) { - int n = 1000; - if (args.length > 0) n = Integer.parseInt(args[0]); - - long start = System.nanoTime(); - double number = 0; - for (int i = 0; i < 10; i++) { - number = spectralnormGame(n); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.3f seconds to run%n", time / 1e10); - System.out.println(formatter.format(number)); - } - - - private static final double spectralnormGame(int n) { - // create unit vector - double[] u = new double[n]; - double[] v = new double[n]; - double[] tmp = new double[n]; - - for (int i = 0; i < n; i++) - u[i] = 1.0; - - // get available processor, then set up syn object - int nthread = Runtime.getRuntime().availableProcessors(); - Approximate.barrier = new CyclicBarrier(nthread); - - int chunk = n / nthread; - Approximate[] ap = new Approximate[nthread]; - - for (int i = 0; i < nthread; i++) { - int r1 = i * chunk; - int r2 = (i < (nthread - 1)) ? r1 + chunk : n; - - ap[i] = new Approximate(u, v, tmp, r1, r2); - } - - - double vBv = 0, vv = 0; - for (int i = 0; i < nthread; i++) { - try { - ap[i].join(); - - vBv += ap[i].m_vBv; - vv += ap[i].m_vv; - } catch (Exception e) { - e.printStackTrace(); - } - } - - return Math.sqrt(vBv / vv); - } - - - private static class Approximate extends Thread { - private static CyclicBarrier barrier; - - private double[] _u; - private double[] _v; - private double[] _tmp; - - private int range_begin, range_end; - private double m_vBv = 0, m_vv = 0; - - - public Approximate(double[] u, double[] v, double[] tmp, int rbegin, int rend) { - super(); - - _u = u; - _v = v; - _tmp = tmp; - - range_begin = rbegin; - range_end = rend; - - start(); - } - - public void run() { - // 20 steps of the power method - for (int i = 0; i < 10; i++) { - MultiplyAtAv(_u, _tmp, _v); - MultiplyAtAv(_v, _tmp, _u); - } - - for (int i = range_begin; i < range_end; i++) { - m_vBv += _u[i] * _v[i]; - m_vv += _v[i] * _v[i]; - } - } - - /* return element i,j of infinite matrix A */ - private final static double eval_A(int i, int j) { - int div = (((i + j) * (i + j + 1) >>> 1) + i + 1); - return 1.0 / div; - } - - /* multiply vector v by matrix A, each thread evaluate its range only */ - private final void MultiplyAv(final double[] v, double[] Av) { - for (int i = range_begin; i < range_end; i++) { - double sum = 0; - for (int j = 0; j < v.length; j++) - sum += eval_A(i, j) * v[j]; - - Av[i] = sum; - } - } - - /* multiply vector v by matrix A transposed */ - private final void MultiplyAtv(final double[] v, double[] Atv) { - for (int i = range_begin; i < range_end; i++) { - double sum = 0; - for (int j = 0; j < v.length; j++) - sum += eval_A(j, i) * v[j]; - - Atv[i] = sum; - } - } - - /* multiply vector v by matrix A and then by matrix A transposed */ - private final void MultiplyAtAv(final double[] v, double[] tmp, double[] AtAv) { - try { - MultiplyAv(v, tmp); - // all thread must syn at completion - barrier.await(); - MultiplyAtv(tmp, AtAv); - // all thread must syn at completion - barrier.await(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } -} \ No newline at end of file diff --git a/src/test/java/com/google/code/java/core/sizeof/GarbageTest.java b/src/test/java/com/google/code/java/core/sizeof/GarbageTest.java deleted file mode 100644 index 91e9a07..0000000 --- a/src/test/java/com/google/code/java/core/sizeof/GarbageTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.sizeof; - -import org.junit.Test; - -import java.io.File; -import java.io.IOException; -import java.nio.channels.Selector; - -public class GarbageTest { - @Test - public void testFileExists() throws IOException { - System.out.printf("The average size of calling File.exists/lastModified/length() is %.1f bytes%n", new SizeofUtil() { - private File file = new File("/tmp/temporary.file"); - - @Override - protected int create() { - file.exists(); - file.lastModified(); - file.length(); - return 1; - } - }.averageBytes()); - } - - @Test - public void testSelectorSelectNow() throws IOException { - final Selector selector = Selector.open(); - System.out.printf("The average size of calling Selector.selectNow() is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - try { - selector.selectNow(); - } catch (IOException e) { - throw new AssertionError(e); - } - return 1; - } - }.averageBytes()); - } -} diff --git a/src/test/java/com/google/code/java/core/sizeof/MemoryUsageExamplesTest.java b/src/test/java/com/google/code/java/core/sizeof/MemoryUsageExamplesTest.java deleted file mode 100644 index 40826c8..0000000 --- a/src/test/java/com/google/code/java/core/sizeof/MemoryUsageExamplesTest.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.sizeof; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.BitSet; -import java.util.LinkedList; - -public class MemoryUsageExamplesTest { - @Test - public void testStringPlus() { - - System.out.printf("The average memory used by StringBuilder for \"abc\" + \"def\" is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - StringBuilder a2f = new StringBuilder().append("abc").append("def"); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by a new \"abcdef\" String is %.1f bytes%n", new SizeofUtil() { - char[] chars = "abcdef".toCharArray(); - - @Override - protected int create() { - String a2f = new String(chars); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by \"abc\" + \"def\" is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - String a2c = "abc"; - String a2f = a2c + "def"; - return 1; - } - }.averageBytes()); - } - - @Test - public void testArray() { - System.out.printf("The average memory used by new BitSet(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - BitSet array = new BitSet(1024); - for (int i = 0; i < array.length(); i++) array.set(i, i % 2 == 0); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by boolean[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - boolean[] array = new boolean[1024]; - for (int i = 0; i < array.length; i++) array[i] = i % 2 == 0; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Boolean[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Boolean[] array = new Boolean[1024]; - for (int i = 0; i < array.length; i++) array[i] = i % 2 == 0; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new ArrayList(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - ArrayList array = new ArrayList(1024); - for (int i = 0; i < 1024; i++) array.add(i, i % 2 == 0); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new LinkedList() with 1024 elements is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - LinkedList array = new LinkedList(); - for (int i = 0; i < 1024; i++) array.add(i, i % 2 == 0); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by byte[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - byte[] array = new byte[1024]; - for (int i = 0; i < array.length; i++) array[i] = (byte) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Byte[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Byte[] array = new Byte[1024]; - for (int i = 0; i < array.length; i++) array[i] = (byte) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new ArrayList(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - ArrayList array = new ArrayList(1024); - for (int i = 0; i < 1024; i++) array.add(i, (byte) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new LinkedList() with 1024 elements is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - LinkedList array = new LinkedList(); - for (int i = 0; i < 1024; i++) array.add(i, (byte) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by char[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - char[] array = new char[1024]; - for (int i = 0; i < array.length; i++) array[i] = (char) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Character[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Character[] array = new Character[1024]; - for (int i = 0; i < array.length; i++) array[i] = (char) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by short[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - short[] array = new short[1024]; - for (int i = 0; i < array.length; i++) array[i] = (short) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Short[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Short[] array = new Short[1024]; - for (int i = 0; i < array.length; i++) array[i] = (short) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new ArrayList(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - ArrayList array = new ArrayList(1024); - for (int i = 0; i < 1024; i++) array.add(i, (short) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new LinkedList() with 1024 elements is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - LinkedList array = new LinkedList(); - for (int i = 0; i < 1024; i++) array.add(i, (short) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by int[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - int[] ints = new int[1024]; - for (int i = 0; i < ints.length; i++) ints[i] = i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Integer[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Integer[] ints = new Integer[1024]; - for (int i = 0; i < ints.length; i++) ints[i] = i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new ArrayList(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - ArrayList array = new ArrayList(1024); - for (int i = 0; i < 1024; i++) array.add(i, (int) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new LinkedList() with 1024 elements is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - LinkedList array = new LinkedList(); - for (int i = 0; i < 1024; i++) array.add(i, (int) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by float[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - float[] array = new float[1024]; - for (int i = 0; i < array.length; i++) array[i] = (float) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Float[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Float[] array = new Float[1024]; - for (int i = 0; i < array.length; i++) array[i] = (float) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by long[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - long[] array = new long[1024]; - for (int i = 0; i < array.length; i++) array[i] = (long) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Long[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Long[] array = new Long[1024]; - for (int i = 0; i < array.length; i++) array[i] = (long) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new ArrayList(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - ArrayList array = new ArrayList(1024); - for (int i = 0; i < 1024; i++) array.add(i, (long) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new LinkedList() with 1024 elements is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - LinkedList array = new LinkedList(); - for (int i = 0; i < 1024; i++) array.add(i, (long) i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by double[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - double[] array = new double[1024]; - for (int i = 0; i < array.length; i++) array[i] = (double) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by Double[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - Double[] array = new Double[1024]; - for (int i = 0; i < array.length; i++) array[i] = (double) i; - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by String[1024] is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - String[] array = new String[1024]; - for (int i = 0; i < array.length; i++) array[i] = String.valueOf(i); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new ArrayList(1024) is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - ArrayList array = new ArrayList(1024); - for (int i = 0; i < 1024; i++) array.add(i, String.valueOf(i)); - return 1; - } - }.averageBytes()); - System.out.printf("The average memory used by new LinkedList() with 1024 elements is %.1f bytes%n", new SizeofUtil() { - @Override - protected int create() { - LinkedList array = new LinkedList(); - for (int i = 0; i < 1024; i++) array.add(i, String.valueOf(i)); - return 1; - } - }.averageBytes()); - } -} diff --git a/src/test/java/com/google/code/java/core/sizeof/SizeOfMapsTest.java b/src/test/java/com/google/code/java/core/sizeof/SizeOfMapsTest.java deleted file mode 100644 index 105016c..0000000 --- a/src/test/java/com/google/code/java/core/sizeof/SizeOfMapsTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.sizeof; - -import gnu.trove.TIntLongHashMap; -import gnu.trove.decorator.TIntLongHashMapDecorator; -import javolution.util.FastMap; -import org.junit.Test; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentSkipListMap; - -public class SizeOfMapsTest { - @Test - public void sizeOfMaps() { - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new TIntLongHashMapDecorator(new TIntLongHashMap(capacity)); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return FastMap.newInstance(); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new IdentityHashMap(capacity * 4 / 3); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new ConcurrentSkipListMap(); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new TreeMap(); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new HashMap(capacity * 4 / 3); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return Collections.synchronizedMap(new HashMap(capacity * 4 / 3)); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new ConcurrentHashMap(capacity * 4 / 3); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return (Map) new Properties(); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new Hashtable(capacity); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new LinkedHashMap(capacity * 4 / 3); - } - }); - sizePerEntry(new Builder>() { - @Override - public Map build(int capacity) { - return new WeakHashMap(capacity * 4 / 3); - } - }); - } - - interface Builder { - T build(int capacity); - } - - private static void sizePerEntry(final Builder> mapBuilder) { - Object build = mapBuilder.build(16); - if (build instanceof TIntLongHashMapDecorator) - build = ((TIntLongHashMapDecorator) build).getMap(); - System.out.printf("The average size of a %s per entry with 16/1024 entries is %.1f/%.1f bytes%n", - build.getClass().getSimpleName(), - new SizeofUtil() { - Map map; - - @Override - protected int create() { - map = mapBuilder.build(16); - populate(map, 16); - return 16; - } - }.averageBytes(), - new SizeofUtil() { - Map map; - - @Override - protected int create() { - map = mapBuilder.build(1024); - populate(map, 1024); - return 1024; - } - }.averageBytes()); - } - - static void populate(Map map, long entries) { - if (map instanceof TIntLongHashMapDecorator) { - TIntLongHashMap _map = ((TIntLongHashMapDecorator) map).getMap(); - for (int i = 0; i < entries; i++) - _map.put(i * 65, i * 65); - } else { - for (int i = 0; i < entries; i++) - map.put(i * 65, i * 65L); - } - if (map instanceof FastMap) - FastMap.recycle((FastMap) map); - } -} diff --git a/src/test/java/com/google/code/java/core/sizeof/SizeofUtilTest.java b/src/test/java/com/google/code/java/core/sizeof/SizeofUtilTest.java deleted file mode 100644 index 5bc026f..0000000 --- a/src/test/java/com/google/code/java/core/sizeof/SizeofUtilTest.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.sizeof; - -import org.joda.time.DateTime; -import org.junit.Test; - -import java.util.AbstractMap; -import java.util.BitSet; -import java.util.Calendar; -import java.util.concurrent.atomic.AtomicReference; - -import static junit.framework.Assert.assertEquals; - -public class SizeofUtilTest { - @Test - public void testAverageBytes() throws Exception { - assertEquals(4.0, new SizeofUtil() { - int[] array; - - @Override - protected int create() { - array = new int[1024]; - return array.length; - } - }.averageBytes(), 0.02); - - assertEquals(1.0 / 8, new SizeofUtil() { - BitSet bits; - - @Override - protected int create() { - bits = new BitSet(1024 * 1024); - return bits.size(); - } - }.averageBytes(), 1e-4); - } - - @Test - public void testHeaderSize() { - System.out.printf("The average size of an int is %.1f bytes%n", new SizeofUtil() { - int[] obj = null; - - @Override - protected int create() { - obj = new int[1024]; - return obj.length; - } - }.averageBytes()); - System.out.printf("The average size of an Object is %.1f bytes%n", new SizeofUtil() { - Object obj = null; - - @Override - protected int create() { - obj = new Object(); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of an Integer is %.1f bytes%n", new SizeofUtil() { - Integer obj = null; - - @Override - protected int create() { - obj = new Integer(1); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of a Long is %.1f bytes%n", new SizeofUtil() { - Long obj = null; - - @Override - protected int create() { - obj = new Long(1); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of an AtomicReference is %.1f bytes%n", new SizeofUtil() { - AtomicReference obj = null; - - @Override - protected int create() { - obj = new AtomicReference(); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of an SimpleEntry(Map.Entry) is %.1f bytes%n", new SizeofUtil() { - AbstractMap.SimpleEntry obj = null; - - @Override - protected int create() { - obj = new AbstractMap.SimpleEntry(null, null); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of a DateTime is %.1f bytes%n", new SizeofUtil() { - DateTime obj = null; - - @Override - protected int create() { - obj = new DateTime(); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of a Calendar is %.1f bytes%n", new SizeofUtil() { - Calendar obj = null; - - @Override - protected int create() { - obj = Calendar.getInstance(); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of an Exception is %.1f bytes%n", new SizeofUtil() { - Exception obj = null; - - @Override - protected int create() { - obj = new Exception("" + System.currentTimeMillis()); - return 1; - } - }.averageBytes()); - System.out.printf("The average size of a bit in a BitSet is %.3f bytes%n", new SizeofUtil() { - BitSet obj = null; - - @Override - protected int create() { - obj = new BitSet(128 * 1024); - return obj.size(); - } - }.averageBytes()); - } -} diff --git a/src/test/java/com/google/code/java/core/socket/AsyncPingTest.java b/src/test/java/com/google/code/java/core/socket/AsyncPingTest.java deleted file mode 100644 index 455b335..0000000 --- a/src/test/java/com/google/code/java/core/socket/AsyncPingTest.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.socket; - -import org.junit.Test; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.StandardSocketOptions; -import java.nio.ByteBuffer; -import java.nio.channels.AsynchronousServerSocketChannel; -import java.nio.channels.AsynchronousSocketChannel; -import java.util.Arrays; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -/** - * Requires Java 7. - */ -public class AsyncPingTest { - @Test - public void testSocketWriteReadLatency() throws IOException, InterruptedException, ExecutionException { - final AsynchronousServerSocketChannel ssc = - AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("localhost", 9999)); - - AsynchronousSocketChannel sc = AsynchronousSocketChannel.open(); - Future connected = sc.connect(new InetSocketAddress("localhost", 9999)); - Future accepted = ssc.accept(); - AsynchronousSocketChannel sc2 = accepted.get(); - configure(sc2); - close(ssc); - connected.get(); - - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - - long times[] = new long[1000 * 1000]; - for (int i = -10000; i < times.length; i++) { - long start = System.nanoTime(); - bb.position(0); - bb.limit(1024); - sc.write(bb); - - bb2.clear(); - sc2.read(bb2).get(); - - bb2.flip(); - sc2.write(bb2); - - bb.clear(); - sc.read(bb).get(); - long end = System.nanoTime(); - long err = System.nanoTime() - end; - long time = end - start - err; - if (i >= 0) - times[i] = time; - } - - close(sc); - close(sc2); - Arrays.sort(times); - System.out.printf("Async Socket latency was 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3 - ); - } - - @Test - public void testSocketWriteReadThroughput() throws IOException, InterruptedException, ExecutionException { - final AsynchronousServerSocketChannel ssc = - AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("localhost", 9999)); - - AsynchronousSocketChannel sc = AsynchronousSocketChannel.open(); - Future connected = sc.connect(new InetSocketAddress("localhost", 9999)); - Future accepted = ssc.accept(); - AsynchronousSocketChannel sc2 = accepted.get(); - configure(sc2); - close(ssc); - connected.get(); - - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - - long start = System.nanoTime(); - int runs = 1000 * 1000; - for (int i = 0; i < runs; i++) { - bb.position(0); - bb.limit(1024); - sc.write(bb); - - bb2.clear(); - sc2.read(bb2).get(); - bb2.flip(); - sc2.write(bb2); - - bb.clear(); - sc.read(bb).get(); - } - long time = System.nanoTime() - start; - - close(sc); - close(sc2); - System.out.printf("Async Socket Throughput was %,d K/s%n", runs * 1000000L / time); - } - - @Test - public void testSocketLatency() throws IOException, InterruptedException, ExecutionException { - final AsynchronousServerSocketChannel ssc = - AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("localhost", 9999)); - - AsynchronousSocketChannel sc = AsynchronousSocketChannel.open(); - Future connected = sc.connect(new InetSocketAddress("localhost", 9999)); - - Thread server = new Thread(new Runnable() { - public void run() { - AsynchronousSocketChannel sc2 = null; - try { - Future accepted = ssc.accept(); - sc2 = accepted.get(); - close(ssc); - ByteBuffer bb1 = ByteBuffer.allocateDirect(4096); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - Future lastWrite = null; - ByteBuffer bb = bb1; - while (!Thread.interrupted()) { - bb.clear(); - Future integerFuture = sc2.read(bb); - while (!integerFuture.isDone()) { - if (Thread.interrupted()) return; - } - bb.flip(); - // wait for the previous write. - if (lastWrite != null) lastWrite.get(); - lastWrite = sc2.write(bb); - // swap the buffers - bb = (bb == bb1) ? bb2 : bb1; - } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } finally { - close(sc2); - } - } - }); - server.start(); - - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - long times[] = new long[1000 * 1000]; - - connected.get(); - for (int i = -10000; i < times.length; i++) { - long start = System.nanoTime(); - bb.position(0); - bb.limit(32); - sc.write(bb).get(); - - - bb.clear(); - sc.read(bb).get(); - long end = System.nanoTime(); - long err = System.nanoTime() - end; - long time = end - start - err; - if (i >= 0) - times[i] = time; - } - server.interrupt(); - close(sc); - Arrays.sort(times); - System.out.printf("Threaded Async Socket Latency for 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3 - ); - } - - @Test - public void testSocketThreadedThroughput() throws IOException, InterruptedException, ExecutionException { - int messageSize = 512; - - final AsynchronousServerSocketChannel ssc = - AsynchronousServerSocketChannel.open().bind(new InetSocketAddress("localhost", 9999)); - - AsynchronousSocketChannel sc = AsynchronousSocketChannel.open(); - Future connected = sc.connect(new InetSocketAddress("localhost", 9999)); - - Thread server = new Thread(new Runnable() { - public void run() { - AsynchronousSocketChannel sc2 = null; - try { - Future accepted = ssc.accept(); - sc2 = accepted.get(); - close(ssc); - ByteBuffer bb1 = ByteBuffer.allocateDirect(4096); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - Future lastWrite = null; - ByteBuffer bb = bb1; - while (!Thread.interrupted()) { - bb.clear(); - Future integerFuture = sc2.read(bb); - while (!integerFuture.isDone()) { - if (Thread.interrupted()) return; - } - bb.flip(); - // wait for the previous write. - if (lastWrite != null) lastWrite.get(); - lastWrite = sc2.write(bb); - // swap the buffers - bb = (bb == bb1) ? bb2 : bb1; - } - } catch (InterruptedException e) { - e.printStackTrace(); - } catch (ExecutionException e) { - e.printStackTrace(); - } finally { - close(sc2); - } - } - }); - server.start(); - - ByteBuffer bb1 = ByteBuffer.allocateDirect(4096); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - - connected.get(); - - long start = System.nanoTime(); - int runs = 1000 * 1000; - Future lastRead = null; - Future lastWrite = null; - for (int i = 0; i < runs; i += 2) { - bb1.position(0); - bb1.limit(messageSize); - if (lastWrite != null) lastWrite.get(); - Future write1 = sc.write(bb1); - - bb2.position(0); - bb2.limit(messageSize); - write1.get(); - lastWrite = sc.write(bb2); - - if (lastRead != null) lastRead.get(); - bb.clear(); - lastRead = sc.read(bb); - } - server.interrupt(); - server.join(); - long time = System.nanoTime() - start; - close(sc); - System.out.printf("Threaded Async Socket Throughput was %,d K/s%n", runs * 1000000L / time); - } - - static void close(Closeable sc2) { - if (sc2 != null) try { - sc2.close(); - } catch (IOException ignored) { - } - } - - - static void configure(AsynchronousSocketChannel sc) throws IOException { - sc.setOption(StandardSocketOptions.TCP_NODELAY, true); - } -} diff --git a/src/test/java/com/google/code/java/core/socket/PingTest.java b/src/test/java/com/google/code/java/core/socket/PingTest.java deleted file mode 100644 index 36d6e96..0000000 --- a/src/test/java/com/google/code/java/core/socket/PingTest.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.socket; - -import org.junit.Test; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketException; -import java.nio.ByteBuffer; -import java.nio.channels.ClosedByInterruptException; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Arrays; - -public class PingTest { - @Test - public void testSocketWriteReadLatency() throws IOException, InterruptedException { - EchoService es = new EchoService(9999); - - SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", 9999)); - - ByteBuffer bb = ByteBuffer.allocateDirect(1 * 1024); - - long times[] = new long[1000 * 1000]; - for (int i = -11000; i < times.length; i++) { - long start = System.nanoTime(); - bb.position(0); - bb.limit(1024); - sc.write(bb); - - bb.clear(); - sc.read(bb); - long end = System.nanoTime(); - long err = System.nanoTime() - end; - long time = end - start - err; - if (i >= 0) - times[i] = time; - } - - es.stop(); - close(sc); - Arrays.sort(times); - System.out.printf("Socket latency was 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3 - ); - } - - @Test - public void testSocketWriteReadThroughput() throws IOException, InterruptedException { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(new InetSocketAddress("localhost", 9999)); - - SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", 9999)); - configure(sc); - SocketChannel sc2 = ssc.accept(); - configure(sc2); - close(ssc); - - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - - long start = System.nanoTime(); - int runs = 1000 * 1000; - for (int i = 0; i < runs; i++) { - bb.position(0); - bb.limit(1024); - sc.write(bb); - - bb2.clear(); - sc2.read(bb2); - bb2.flip(); - sc2.write(bb2); - - bb.clear(); - sc.read(bb); - } - long time = System.nanoTime() - start; - - close(sc); - close(sc2); - System.out.printf("Socket Throughput was %,d K/s%n", runs * 1000000L / time); - } - - @Test - public void testSocketLatency() throws IOException, InterruptedException { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(new InetSocketAddress("localhost", 9999)); - Thread server = new Thread(new Runnable() { - public void run() { - SocketChannel sc2 = null; - try { - sc2 = ssc.accept(); - configure(sc2); - sc2.configureBlocking(false); - close(ssc); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - while (!Thread.interrupted()) { - bb2.clear(); - do { - sc2.read(bb2); - } while (bb2.position() == 0); - bb2.flip(); - sc2.write(bb2); - } - } catch (ClosedByInterruptException ignored) { - } catch (ClosedChannelException ignored) { - } catch (IOException e) { - e.printStackTrace(); - } finally { - close(sc2); - } - } - }); - server.start(); - SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", 9999)); - configure(sc); - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - long times[] = new long[1000 * 1000]; - for (int i = -10000; i < times.length; i++) { - long start = System.nanoTime(); - bb.position(0); - bb.limit(32); - sc.write(bb); - - - bb.clear(); - sc.read(bb); - long end = System.nanoTime(); - long err = System.nanoTime() - end; - long time = end - start - err; - if (i >= 0) - times[i] = time; - } - server.interrupt(); - close(sc); - Arrays.sort(times); - System.out.printf("Threaded Socket Latency for 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3 - ); - } - - @Test - public void testSocketThreadedThroughput() throws IOException, InterruptedException { - final ServerSocketChannel ssc = ServerSocketChannel.open(); - ssc.socket().bind(new InetSocketAddress("localhost", 9999)); - - Thread server = new Thread(new Runnable() { - @Override - public void run() { - SocketChannel sc2 = null; - try { - sc2 = ssc.accept(); - configure(sc2); - close(ssc); - ByteBuffer bb2 = ByteBuffer.allocateDirect(4096); - while (!Thread.interrupted()) { - bb2.clear(); - sc2.read(bb2); - bb2.flip(); - sc2.write(bb2); - } - } catch (ClosedByInterruptException ignored) { - } catch (ClosedChannelException ignored) { - } catch (IOException e) { - e.printStackTrace(); - } finally { - close(sc2); - } - } - }); - server.start(); - SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", 9999)); - configure(sc); - - ByteBuffer bb = ByteBuffer.allocateDirect(4096); - - long start = System.nanoTime(); - int runs = 1000 * 1000; - for (int i = 0; i < runs; i += 2) { - bb.position(0); - bb.limit(1024); - sc.write(bb); - - bb.position(0); - bb.limit(1024); - sc.write(bb); - - bb.clear(); - sc.read(bb); - } - server.interrupt(); - server.join(); - long time = System.nanoTime() - start; - close(sc); - System.out.printf("Threaded Socket Throughput was %,d K/s%n", runs * 1000000L / time); - } - - static void close(Closeable sc2) { - if (sc2 != null) try { - sc2.close(); - } catch (IOException ignored) { - } - } - - - static void configure(SocketChannel sc) throws SocketException { - sc.socket().setTcpNoDelay(true); - } -} diff --git a/src/test/java/com/google/code/java/core/socket/SocketThroughputTest.java b/src/test/java/com/google/code/java/core/socket/SocketThroughputTest.java deleted file mode 100644 index fed34b9..0000000 --- a/src/test/java/com/google/code/java/core/socket/SocketThroughputTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.socket; - -import org.junit.Test; - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; - -/* -Java 6 update 26 -With 1 clients, transfer rate of 1,332 MB/s -With 2 clients, transfer rate of 2,218 MB/s -With 4 clients, transfer rate of 3,522 MB/s -With 8 clients, transfer rate of 4,538 MB/s -With 16 clients, transfer rate of 4,344 MB/s -With 32 clients, transfer rate of 4,086 MB/s -With 100 clients, transfer rate of 3,823 MB/s -With 300 clients, transfer rate of 3,906 MB/s -With 1,000 clients, transfer rate of 3,898 MB/s - -Java 7 update 1 -With 1 clients, transfer rate of 1,064 MB/s -With 2 clients, transfer rate of 2,132 MB/s -With 4 clients, transfer rate of 3,390 MB/s -With 8 clients, transfer rate of 3,945 MB/s -With 16 clients, transfer rate of 4,078 MB/s -With 32 clients, transfer rate of 4,055 MB/s -With 100 clients, transfer rate of 3,965 MB/s -With 300 clients, transfer rate of 3,892 MB/s -With 1,000 clients, transfer rate of 3,913 MB/s - */ - -public class SocketThroughputTest { - @Test - public void testThroughput() throws IOException, InterruptedException { - for (int clients : new int[]{1, 2, 4, 8, 16, 32, 100, 300, 1000, 2500, 5000, 10000}) { - doTest(clients, 64 * 1024, 8L * 1024 * 1024 * 1024); - } - } - - public void doTest(final int clients, final int blockSize, final long size) throws IOException, InterruptedException { - long start = System.nanoTime(); -// EchoService echo = new EchoService(12345); - ExecutorService es = Executors.newCachedThreadPool(); - final AtomicLong size2 = new AtomicLong(); - for (int i = 0; i < clients; i++) { - final SocketChannel sc = SocketChannel.open(new InetSocketAddress("localhost", 12345)); - es.execute(new Runnable() { - @Override - public void run() { - ByteBuffer bb = ByteBuffer.allocateDirect(blockSize); - try { - for (long i = 0; i < size; i += blockSize * clients) { - bb.clear(); - while (bb.remaining() > 0) sc.write(bb); - - bb.clear(); - while (bb.remaining() > 0) sc.read(bb); - size2.addAndGet(blockSize); - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - try { - sc.close(); - } catch (IOException ignored) { - } - } - } - }); - } - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - -// echo.stop(); - long time = System.nanoTime() - start; - long rate = size2.get() * 1000000L / 1024 / 1024 * 1000 / time; - System.out.printf("With %,d clients, transfer rate of %,d MB/s%n", clients, rate); - } -} diff --git a/src/test/java/com/google/code/java/core/socket/XmlServiceTest.java b/src/test/java/com/google/code/java/core/socket/XmlServiceTest.java deleted file mode 100644 index 7311fd3..0000000 --- a/src/test/java/com/google/code/java/core/socket/XmlServiceTest.java +++ /dev/null @@ -1,528 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.socket; - -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.junit.Test; - -import java.io.Closeable; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.nio.BufferUnderflowException; -import java.nio.ByteBuffer; -import java.nio.ByteOrder; -import java.nio.channels.ClosedChannelException; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Arrays; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicInteger; - -import static junit.framework.Assert.assertEquals; - -public class XmlServiceTest { - @Test - public void xmlServiceRoundTrip() throws IOException { - HeartbeatServer hs = new HeartbeatServer(9999); - hs.start(); - int runs = 3 * 1000 * 1000; - - final AtomicInteger count = new AtomicInteger(); - final long[] times = new long[runs]; - EventListener el = new EventListener() { - @Override - public void heartbeatRequest(long timestamp, long sequenceNumber) { - // ignore - } - - @Override - public void heartbeatResponse(long timestamp, long sequenceNumber) { - int n = count.getAndIncrement(); - times[n] = System.nanoTime() - sequenceNumber; - } - - @Override - public void error(String message) { - System.err.println("client: " + message); - } - }; - SocketChannel sc = SocketChannel.open(new InetSocketAddress(9999)); - ByteBuffer wb = ByteBuffer.allocateDirect(4 * 1024); - XmlEventParser xep = new XmlEventParser(); - for (int i = 0; i < runs; i += 2) { - writeHeartbeatRequest(sc, wb, System.nanoTime()); - writeHeartbeatRequest(sc, wb, System.nanoTime()); - ByteBuffer rb = xep.bufferForWriting(128); - sc.read(rb); - xep.process(el); - } - // read remaining responses. - while (count.get() < runs) { - ByteBuffer rb = xep.bufferForWriting(128); - sc.read(rb); - xep.process(el); - } - hs.stop(); - Arrays.sort(times); - System.out.printf("Socket latency was 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[times.length / 100] / 1e3, - times[times.length / 2] / 1e3, - times[times.length - times.length / 100 - 1] / 1e3 - ); - - } - - @Test - public void xmlServiceThroughput() throws IOException { - HeartbeatServer hs = new HeartbeatServer(9999); - hs.start(); - int runs = 3 * 1000 * 1000; - - final AtomicInteger count = new AtomicInteger(); - EventListener el = new EventListener() { - @Override - public void heartbeatRequest(long timestamp, long sequenceNumber) { - // ignore - } - - @Override - public void heartbeatResponse(long timestamp, long sequenceNumber) { - count.getAndIncrement(); - } - - @Override - public void error(String message) { - System.err.println("client: " + message); - } - }; - SocketChannel sc = SocketChannel.open(new InetSocketAddress(9999)); - ByteBuffer wb = ByteBuffer.allocateDirect(64 * 1024); - XmlEventParser xep = new XmlEventParser(); - long start = System.nanoTime(); - for (int i = 0; i < runs; i += 2) { - writeHeartbeatRequest(sc, wb, System.nanoTime()); - writeHeartbeatRequest(sc, wb, System.nanoTime()); - ByteBuffer rb = xep.bufferForWriting(8 * 1024); - sc.read(rb); - xep.process(el); - } - // read remaining responses. - while (count.get() < runs) { - ByteBuffer rb = xep.bufferForWriting(8 * 1024); - sc.read(rb); - xep.process(el); - } - long time = System.nanoTime() - start; - hs.stop(); - System.out.printf("Socket throughput was %,d K/s%n", (long) (runs * 1e6 / time)); - - } - - static class HeartbeatServer implements Runnable { - private final ExecutorService executor = Executors.newCachedThreadPool(); - private final ServerSocketChannel ssc; - - HeartbeatServer(int port) throws IOException { - ssc = ServerSocketChannel.open(); - try { - ssc.socket().bind(new InetSocketAddress(port)); - } catch (IOException e) { - close(ssc); - throw e; - } - } - - - public void start() { - executor.submit(this); - } - - public void stop() { - close(ssc); - executor.shutdown(); - } - - @Override - public void run() { - try { - while (!Thread.interrupted()) { - SocketChannel sc = ssc.accept(); - executor.submit(new HeartbeatHandler(sc)); - } - } catch (ClosedChannelException ignored) { - } catch (IOException e) { - e.printStackTrace(); - } - } - - class HeartbeatHandler implements Runnable, EventListener { - private final SocketChannel sc; - private final ByteBuffer wb = ByteBuffer.allocateDirect(64 * 1024); - - public HeartbeatHandler(SocketChannel sc) { - this.sc = sc; - } - - @Override - public void run() { - XmlEventParser parser = new XmlEventParser(); - try { - while (true) { - ByteBuffer bb = parser.bufferForWriting(8 * 1024); - sc.read(bb); - parser.process(this); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void heartbeatRequest(long timestamp, long sequenceNumber) { - try { - writeHeartbeatResponse(sc, wb, sequenceNumber); - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Override - public void heartbeatResponse(long timestamp, long sequenceNumber) { - // ignore. - } - - @Override - public void error(String message) { - System.err.println("server: " + message); - } - } - - } - - static interface EventListener { - void heartbeatRequest(long timestamp, long sequenceNumber); - - void heartbeatResponse(long timestamp, long sequenceNumber); - - void error(String message); - } - - static class XmlEventParser { - private final ByteBuffer buffer = ByteBuffer.allocateDirect(64 * 1024); { - buffer.order(ByteOrder.nativeOrder()); - } - - private int readOffset = 0; - private int writeOffset = 0; - private XmlState state = XmlState.ROOT; - private long timestamp = 0; - - public ByteBuffer bufferForWriting(int capacity) { - if (writeOffset + capacity > buffer.capacity()) { - if (buffer.position() == 0) throw new IllegalArgumentException("Capacity too large"); - buffer.limit(writeOffset); - buffer.position(readOffset); - buffer.compact(); - writeOffset -= readOffset; - readOffset = 0; - } - buffer.limit(buffer.capacity()); - buffer.position(writeOffset); - return buffer; - } - - public void process(EventListener listener) { - // save write position. - writeOffset = buffer.position(); - // reset for read. - buffer.limit(writeOffset); - buffer.position(readOffset); - int position = readOffset; - - try { - while (state.requires() <= buffer.remaining()) { - state = state.process(this, buffer, listener); - position = buffer.position(); - } - } catch (BufferUnderflowException e) { - // needs to read more data. - } - readOffset = position; - - } - - /* - - or - - */ - private static final int ROOT = ('<' << 24) + ('R' << 16) + ('o' << 8) + ('o' << 0); - private static final int ROOT2 = ('<' << 0) + ('R' << 8) + ('o' << 16) + ('o' << 24); - - enum XmlState { - ROOT { - private final int requires = "".length(); - private final int ROOT_TAIL_LENGTH = "t timestamp=\"".length(); - - @Override - int requires() { - return requires; - } - - @Override - XmlState process(XmlEventParser xep, ByteBuffer bb, EventListener listener) { - int word = bb.getInt(); - switch (word) { - case XmlEventParser.ROOT: - case XmlEventParser.ROOT2: - int length = ROOT_TAIL_LENGTH; - windForward(bb, length); - return READ_TIMESTAMP; - default: - listener.error("Invalid start of XML message, ignoring."); - bb.position(bb.position() - 3); - return CONSUME_UNTIL_ROOT; - } - } - }, - READ_TIMESTAMP { - private final int requires = "1\">".length(); - private final int END_LENGTH = ">".length(); - - @Override - int requires() { - return requires; - } - - @Override - XmlState process(XmlEventParser xep, ByteBuffer bb, EventListener listener) { - xep.timestamp = readLong(bb); - windForward(bb, END_LENGTH); - return REQUEST; - } - }, - REQUEST { - // the shortest complete request - private final int requires = "".length(); - private final int SKIP = "".length(); - private final int END_LENGTH = "/>\n".length(); - - @Override - int requires() { - return requires; - } - - @Override - XmlState process(XmlEventParser xep, ByteBuffer bb, EventListener listener) { - long sequence = readLong(bb); - windForward(bb, END_LENGTH); - listener.heartbeatRequest(xep.timestamp, sequence); - return ROOT; - } - }, - HEARTBEAT_RESPONSE { - private final int requires = "1\">".length(); - private final int END_LENGTH = "/>\n".length(); - - @Override - int requires() { - return requires; - } - - @Override - XmlState process(XmlEventParser xep, ByteBuffer bb, EventListener listener) { - long sequence = readLong(bb); - windForward(bb, END_LENGTH); - listener.heartbeatResponse(xep.timestamp, sequence); - return ROOT; - } - }, - CONSUME_UNTIL_ROOT { - @Override - int requires() { - return 4; - } - - @Override - XmlState process(XmlEventParser xep, ByteBuffer bb, EventListener listener) { - int word = bb.getInt(); - switch (word) { - case XmlEventParser.ROOT: - case XmlEventParser.ROOT2: - bb.position(bb.position() - 4); - return READ_TIMESTAMP; - default: - bb.position(bb.position() - 3); - return CONSUME_UNTIL_ROOT; - } - } - }; - - - static void windForward(ByteBuffer bb, int length) { - if (length > bb.remaining()) throw new BufferUnderflowException(); - bb.position(bb.position() + length); - } - - abstract int requires(); - - abstract XmlState process(XmlEventParser xep, ByteBuffer bb, EventListener listener); - } - } - - public static long readLong(ByteBuffer bb) { - long value = 0; - boolean negative = false; - while (true) { - byte b = bb.get(); - if (b >= '0' && b <= '9') { - value = value * 10 + b - '0'; - } else if (b == '-') { - negative = true; - } else { - break; - } - } - return negative ? -value : value; - } - - static final byte[] ROOT_BYTES = "\n".getBytes(); - - static void writeHeartbeatRequest(SocketChannel sc, ByteBuffer wb, long sequenceNumber) throws IOException { - wb.clear(); - wb.put(ROOT_BYTES); - writeLong(wb, System.nanoTime()); - wb.put(REQUEST_BYTES); - writeLong(wb, sequenceNumber); - wb.put(END_ROOT_BYTES); - wb.flip(); - sc.write(wb); - } - - static void writeHeartbeatResponse(SocketChannel sc, ByteBuffer wb, long sequenceNumber) throws IOException { - wb.clear(); - wb.put(ROOT_BYTES); - writeLong(wb, System.nanoTime()); - wb.put(RESPONSE_BYTES); - writeLong(wb, sequenceNumber); - wb.put(END_ROOT_BYTES); - wb.flip(); - sc.write(wb); - } - - private static final byte[] MIN_VALUE_BYTES = Long.toString(Long.MIN_VALUE).getBytes(); - - public static void writeLong(ByteBuffer wb, long l) { - if (l == Long.MIN_VALUE) { - wb.put(MIN_VALUE_BYTES); - } else if (l == 0) { - wb.put((byte) '0'); - } else { - if (l < 0) { - wb.put((byte) '-'); - l = -l; - } - long tens = tensFloor(l); - while (tens > 0) { - wb.put((byte) (l / tens % 10 + '0')); - tens /= 10; - } - } - } - - static final long[] TENS = new long[19]; static { - TENS[0] = 1; - for (int i = 1; i < TENS.length; i++) TENS[i] = TENS[i - 1] * 10; - } - - static long tensFloor(long l) { - int idx = Arrays.binarySearch(TENS, l); - return idx < 0 ? TENS[~idx - 1] : TENS[idx]; - } - - public static void close(Closeable closeable) { - if (closeable != null) try { - closeable.close(); - } catch (IOException ignored) { - } - } - - @Test - public void testWriteReadLong() { - ByteBuffer bb = ByteBuffer.allocate(4 * 1024); - for (long l = Long.MIN_VALUE; l < 0; l /= 2) { - writeLong(bb, l); - bb.put((byte) '\n'); - writeLong(bb, ~l); - bb.put((byte) '\n'); - } -// System.out.println(new String(bb.array(), 0, bb.position())); - bb.flip(); - for (long l = Long.MIN_VALUE; l < 0; l /= 2) { - assertEquals(l, readLong(bb)); - assertEquals(~l, readLong(bb)); - } - } - - @Test - public void testXmlEventParser() { - Mockery mock = new Mockery(); - final EventListener el = mock.mock(EventListener.class); - mock.checking(new Expectations() {{ - oneOf(el).heartbeatRequest(123456789, 1); - }}); - - XmlEventParser xep = new XmlEventParser(); - ByteBuffer bb = xep.bufferForWriting(256); - bb.put("\n".getBytes()); - xep.process(el); - mock.assertIsSatisfied(); - - mock.checking(new Expectations() {{ - oneOf(el).heartbeatResponse(123456790, 2); - }}); - bb = xep.bufferForWriting(256); - bb.put("\n".getBytes()); - xep.process(el); - mock.assertIsSatisfied(); - } -} diff --git a/src/test/java/com/google/code/java/core/threads/IncrementNotThreadSafeMain.java b/src/test/java/com/google/code/java/core/threads/IncrementNotThreadSafeMain.java deleted file mode 100644 index ab5fa52..0000000 --- a/src/test/java/com/google/code/java/core/threads/IncrementNotThreadSafeMain.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.threads; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class IncrementNotThreadSafeMain { - public static void main(String... args) throws InterruptedException { - for (int nThreads = 1; nThreads <= 64; nThreads *= 2) - doThreadSafeTest(nThreads); - } - - static class VolatileInt { - volatile int num = 0; - } - - private static void doThreadSafeTest(final int nThreads) throws InterruptedException { - final int count = 100 * 1000 * 1000; - - ExecutorService es = Executors.newFixedThreadPool(nThreads); - final VolatileInt vi = new VolatileInt(); -// final AtomicInteger num = new AtomicInteger(); - for (int i = 0; i < nThreads; i++) - es.submit(new Runnable() { - public void run() { - for (int j = 0; j < count; j += nThreads) - vi.num++; -// num.incrementAndGet(); - } - }); - es.shutdown(); - es.awaitTermination(1, TimeUnit.MINUTES); - assert es.isTerminated(); - System.out.printf("With %,d threads should total %,d but was %,d%n", nThreads, count, vi.num /*num.longValue()*/); - } - -} diff --git a/src/test/java/com/google/code/java/core/threads/MaxThreadsMain.java b/src/test/java/com/google/code/java/core/threads/MaxThreadsMain.java deleted file mode 100644 index cba8360..0000000 --- a/src/test/java/com/google/code/java/core/threads/MaxThreadsMain.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.threads; - -import java.util.ArrayList; -import java.util.List; - -public class MaxThreadsMain { - - public static final int BATCH_SIZE = 4000; - - public static void main(String... args) throws InterruptedException { - List threads = new ArrayList(); - try { - for (int i = 0; i <= 100 * 1000; i += BATCH_SIZE) { - long start = System.currentTimeMillis(); - addThread(threads, BATCH_SIZE); - long end = System.currentTimeMillis(); - Thread.sleep(1000); - long delay = end - start; - System.out.printf("%,d threads: Time to create %,d threads was %.3f seconds %n", threads.size(), BATCH_SIZE, delay / 1e3); - } - } catch (Throwable e) { - System.err.printf("After creating %,d threads, ", threads.size()); - e.printStackTrace(); - } - - } - - private static void addThread(List threads, int num) { - for (int i = 0; i < num; i++) { - Thread t = new Thread(new Runnable() { - @Override - public void run() { - try { - while (!Thread.interrupted()) { - Thread.sleep(1000); - } - } catch (InterruptedException ignored) { - // - } - } - }); - t.setDaemon(true); - t.setPriority(Thread.MIN_PRIORITY); - threads.add(t); - t.start(); - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/ParallelSortMain.java b/src/test/java/com/google/code/java/core/threads/ParallelSortMain.java deleted file mode 100644 index c46dee0..0000000 --- a/src/test/java/com/google/code/java/core/threads/ParallelSortMain.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.threads; - -import java.util.Arrays; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -public class ParallelSortMain { - public static void main(String... args) throws InterruptedException { - Random rand = new Random(); - final int[] values = new int[100 * 1024 * 1024]; - for (int i = 0; i < values.length; i++) - values[i] = rand.nextInt(); - - int threads = Runtime.getRuntime().availableProcessors(); - ExecutorService es = Executors.newFixedThreadPool(threads); - int blockSize = (values.length + threads - 1) / threads; - for (int i = 0; i < values.length; i += blockSize) { - final int min = i; - final int max = Math.min(min + blockSize, values.length); - es.submit(new Runnable() { - @Override - public void run() { - Arrays.sort(values, min, max); - } - }); - } - es.shutdown(); - es.awaitTermination(10, TimeUnit.MINUTES); - for (int blockSize2 = blockSize; blockSize2 < values.length / 2; blockSize2 *= 2) { - for (int i = 0; i < values.length; i += blockSize2) { - final int min = i; - final int mid = Math.min(min + blockSize2, values.length); - final int max = Math.min(min + blockSize2 * 2, values.length); - mergeSort(values, min, mid, max); - } - } - } - - private static boolean mergeSort(int[] values, int left, int mid, int end) { - int[] results = new int[end - left]; - int l = left, r = mid, m = 0; - for (; l < left && r < mid; m++) { - int lv = values[l]; - int rv = values[r]; - if (lv < rv) { - results[m] = lv; - l++; - } else { - results[m] = rv; - r++; - } - } - while (l < mid) - results[m++] = values[l++]; - while (r < end) - results[m++] = values[r++]; - System.arraycopy(results, 0, values, left, results.length); - return false; - } -} diff --git a/src/test/java/com/google/code/java/core/threads/RequiresVolatileMain.java b/src/test/java/com/google/code/java/core/threads/RequiresVolatileMain.java deleted file mode 100644 index dba6450..0000000 --- a/src/test/java/com/google/code/java/core/threads/RequiresVolatileMain.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.google.code.java.core.threads; - -/** - * @author peter.lawrey - */ -public class RequiresVolatileMain { - static boolean value; - - public static void main(String... args) { - new Thread(new MyRunnable(true), "Sets true").start(); - new Thread(new MyRunnable(false), "Sets false").start(); - } - - private static class MyRunnable implements Runnable { - private final boolean target; - - private MyRunnable(boolean target) { - this.target = target; - } - - @Override - public void run() { - int count = 0; - boolean logged = false; - while (true) { - if (value != target) { - value = target; - count = 0; - if (!logged) - System.out.println(Thread.currentThread().getName() + ": reset value=" + value); - } else if (++count % 1000000000 == 0) { - System.out.println(Thread.currentThread().getName() + ": value=" + value + " target=" + target); - logged = true; - } - } - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/SynchronizedVsLockTest.java b/src/test/java/com/google/code/java/core/threads/SynchronizedVsLockTest.java deleted file mode 100644 index b0edb34..0000000 --- a/src/test/java/com/google/code/java/core/threads/SynchronizedVsLockTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.threads; - -import org.junit.Test; - -import java.util.Map; -import java.util.TreeMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -public class SynchronizedVsLockTest { - static final Object mutex1 = new Object(); - static final Object mutex2 = new Object(); - static final Lock lock1 = new ReentrantLock(); - static final Lock lock2 = new ReentrantLock(); - static int counter1 = 0; - static int counter2 = 0; - static final AtomicInteger counter3 = new AtomicInteger(); - static final AtomicInteger counter4 = new AtomicInteger(); - public static final int LOOPS = 50 * 1000 * 1000; - static final Map results = new TreeMap(); - - @Test - public void testSvL() throws InterruptedException { - testSvL1(); - testSvL2(); - - for (Map.Entry entry : results.entrySet()) { - System.out.print(""); - System.out.print(entry.getKey()); - for (double v : entry.getValue()) { - System.out.print(""); - System.out.printf("%.3f", v); - } - System.out.println(""); - } - } - - static void testSvL1() throws InterruptedException { - for (final int t : new int[]{1, 2, 4, 8, 16, 32, 64}) { - doTest(t, 0, new Runnable() { - @Override - public void run() { - for (int i = 0; i < LOOPS / t; i++) { - synchronized (mutex1) { - counter1++; - } - } - } - - @Override - public String toString() { - return "1x synchronized {}"; - } - }); - doTest(t, 1, new Runnable() { - @Override - public void run() { - for (int i = 0; i < LOOPS / t; i++) { - lock1.lock(); - try { - counter1++; - } finally { - lock1.unlock(); - } - } - } - - @Override - public String toString() { - return "1x Lock.lock()/unlock()"; - } - }); - doTest(t, 2, new Runnable() { - @Override - public void run() { - for (int i = 0; i < LOOPS / t; i++) { - counter3.getAndIncrement(); - } - } - - @Override - public String toString() { - return "1x AtomicInteger"; - } - }); - } - } - - static void testSvL2() throws InterruptedException { - for (final int t : new int[]{1, 2, 4, 8, 16, 32, 64}) { - doTest(t, 3, new Runnable() { - @Override - public void run() { - for (int i = 0; i < LOOPS / t; i++) { - synchronized (mutex1) { - counter1++; - } - synchronized (mutex2) { - counter2++; - } - } - } - - @Override - public String toString() { - return "2x synchronized {}"; - } - }); - doTest(t, 4, new Runnable() { - @Override - public void run() { - for (int i = 0; i < LOOPS / t; i++) { - lock1.lock(); - try { - counter1++; - } finally { - lock1.unlock(); - } - lock2.lock(); - try { - counter2++; - } finally { - lock2.unlock(); - } - } - } - - @Override - public String toString() { - return "2x Lock.lock()/unlock()"; - } - }); - doTest(t, 5, new Runnable() { - @Override - public void run() { - for (int i = 0; i < LOOPS / t; i++) { - counter3.getAndIncrement(); - counter4.getAndIncrement(); - } - } - - @Override - public String toString() { - return "2x AtomicInteger"; - } - }); - } - } - - private static void doTest(int threads, int testNum, Runnable runnable) throws InterruptedException { - ExecutorService es = Executors.newFixedThreadPool(threads); - long start = System.nanoTime(); - try { - for (int i = 0; i < threads; i++) - es.execute(runnable.getClass().getDeclaredConstructor(int.class).newInstance(threads)); - - } catch (Exception e) { - throw new AssertionError(e); - } finally { - es.shutdown(); - } - es.awaitTermination(1, TimeUnit.MINUTES); - long time = (System.nanoTime() - start) / 1000000; - System.out.printf("%s with %d threads took %.3f seconds%n", runnable.toString(), threads, time / 1e3); - double[] times = results.get(threads); - if (times == null) - results.put(threads, times = new double[6]); - times[testNum] = time / 1e3; - } -} diff --git a/src/test/java/com/google/code/java/core/threads/ThreadLatencyTest.java b/src/test/java/com/google/code/java/core/threads/ThreadLatencyTest.java deleted file mode 100644 index b749bcf..0000000 --- a/src/test/java/com/google/code/java/core/threads/ThreadLatencyTest.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (c) 2011. Peter Lawrey - * - * "THE BEER-WARE LICENSE" (Revision 128) - * As long as you retain this notice you can do whatever you want with this stuff. - * If we meet some day, and you think this stuff is worth it, you can buy me a beer in return - * There is no warranty. - */ - -package com.google.code.java.core.threads; - -import org.junit.Test; - -import java.util.Arrays; - -public class ThreadLatencyTest { - enum Pauser { - YIELD { - @Override - public void pause() { - Thread.yield(); - } - }, NO_WAIT { - @Override - public void pause() { - // nothing. - } - }, BUSY_WAIT_10 { - @Override - public void pause() { - long start = System.nanoTime(); - while (System.nanoTime() - start < 10e6) ; - } - }, BUSY_WAIT_3 { - @Override - public void pause() { - long start = System.nanoTime(); - while (System.nanoTime() - start < 3e6) ; - } - }, BUSY_WAIT_1 { - @Override - public void pause() { - long start = System.nanoTime(); - while (System.nanoTime() - start < 1e6) ; - } - }, SLEEP_10 { - @Override - public void pause() throws InterruptedException { - Thread.sleep(10); - } - }, SLEEP_3 { - @Override - public void pause() throws InterruptedException { - Thread.sleep(3); - } - }, SLEEP_1 { - @Override - public void pause() throws InterruptedException { - Thread.sleep(1); - } - }; - - public abstract void pause() throws InterruptedException; - } - - @Test - public void testLatency() throws InterruptedException { - System.out.print("Warmup - "); - doTest(Pauser.NO_WAIT); - - for (Pauser pauser : Pauser.values()) - doTest(pauser); - } - - private void doTest(Pauser delay) throws InterruptedException { - int[] times = new int[1000 * 1000]; - byte[] bytes = new byte[32 * 1024]; - byte[] bytes2 = new byte[32 * 1024]; - long end = System.nanoTime() + (long) 5e9; - int i; - for (i = 0; i < times.length; i++) { - long start = System.nanoTime(); - System.arraycopy(bytes, 0, bytes2, 0, bytes.length); - long time = System.nanoTime() - start; - times[i] = (int) time; - delay.pause(); - if (start > end) break; - } - Arrays.sort(times, 0, i); - System.out.printf(delay + ": Copy memory latency 1/50/99%%tile %.1f/%.1f/%.1f us%n", - times[i / 100] / 1e3, - times[i / 2] / 1e3, - times[i - i / 100 - 1] / 1e3 - ); - } -} diff --git a/src/test/java/com/google/code/java/core/threads/ThreadedAccountLockMain.java b/src/test/java/com/google/code/java/core/threads/ThreadedAccountLockMain.java deleted file mode 100644 index c1b3c4e..0000000 --- a/src/test/java/com/google/code/java/core/threads/ThreadedAccountLockMain.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.google.code.java.core.threads; - -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * @author peter.lawrey - */ -public class ThreadedAccountLockMain { - public static void main(String... args) { - int accountCount = 20 * 1000; - Account[] accounts = new Account[accountCount]; - for (int i = 0; i < accounts.length; i++) accounts[i] = new Account(100); - for (int r = 0; r < 9; r++) { - long start = System.nanoTime(); - for (int i = 0; i < accountCount; i += 2) { - transfer(accounts[i], accounts[i + 1], 10); - transfer(accounts[i + 1], accounts[i], 11); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.1f ns to transfer money with a lock on each Account.%n", (double) time / accountCount); - } - } - - private static void transfer(Account from, Account to, int amount) { - try { - if (from.compareTo(to) <= 0) { - from.lock().lock(); - to.lock().lock(); - } else { - to.lock().lock(); - from.lock().lock(); - } - if (from.balance() < amount) throw new IllegalArgumentException(); - from.transfer(-amount); - to.transfer(amount); - } finally { - to.lock().unlock(); - from.lock().unlock(); - } - } - - - static class Account implements Comparable { - private static final AtomicLong IDS = new AtomicLong(); - private final long id = IDS.getAndIncrement(); - private final Lock lock = new ReentrantLock(); - - private long balance; - - public Account(long balance) { - this.balance = balance; - } - - public Lock lock() { - return lock; - } - - public long balance() { - return balance; - } - - public void transfer(long delta) { - if (delta + balance < 0) throw new IllegalStateException(); - balance += delta; - } - - @Override - public int compareTo(Account o) { - return id > o.id ? +1 : -1; - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/ThreadedAccountMain.java b/src/test/java/com/google/code/java/core/threads/ThreadedAccountMain.java deleted file mode 100644 index 78362cf..0000000 --- a/src/test/java/com/google/code/java/core/threads/ThreadedAccountMain.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.google.code.java.core.threads; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author peter.lawrey - */ -public class ThreadedAccountMain { - public static void main(String... args) { - int accountCount = 20 * 1000; - Account[] accounts = new Account[accountCount]; - for (int i = 0; i < accounts.length; i++) accounts[i] = new Account(100); - for (int r = 0; r < 9; r++) { - long start = System.nanoTime(); - for (int i = 0; i < accountCount; i += 2) { - transfer(accounts[i], accounts[i + 1], 10); - transfer(accounts[i + 1], accounts[i], 11); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.1f ns to transfer money with a synchronized on each Account.%n", (double) time / accountCount); - } - } - - private static void transfer(Account from, Account to, int amount) { - boolean comp = from.compareTo(to) <= 0; - Object firstLock = comp ? from.lock() : to.lock(); - Object secondLock = comp ? to.lock() : from.lock(); - synchronized (firstLock) { - synchronized (secondLock) { - if (from.balance() < amount) throw new IllegalArgumentException(); - from.transfer(-amount); - to.transfer(amount); - } - } - } - - - static class Account implements Comparable { - private static final AtomicLong IDS = new AtomicLong(); - private final long id = IDS.getAndIncrement(); - private final Object lock = new Object(); - - private long balance; - - public Account(long balance) { - this.balance = balance; - } - - public Object lock() { - return lock; - } - - public long balance() { - return balance; - } - - public void transfer(long delta) { - if (delta + balance < 0) throw new IllegalStateException(); - balance += delta; - } - - @Override - public int compareTo(Account o) { - return id > o.id ? +1 : -1; - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/ThreadedAccountOneLockMain.java b/src/test/java/com/google/code/java/core/threads/ThreadedAccountOneLockMain.java deleted file mode 100644 index 33c844b..0000000 --- a/src/test/java/com/google/code/java/core/threads/ThreadedAccountOneLockMain.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.google.code.java.core.threads; - -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -/** - * @author peter.lawrey - */ -public class ThreadedAccountOneLockMain { - public static void main(String... args) { - int accountCount = 20 * 1000; - Account[] accounts = new Account[accountCount]; - for (int i = 0; i < accounts.length; i++) accounts[i] = new Account(100); - for (int r = 0; r < 9; r++) { - long start = System.nanoTime(); - for (int i = 0; i < accountCount; i += 2) { - transfer(accounts, accounts[i], accounts[i + 1], 10); - transfer(accounts, accounts[i + 1], accounts[i], 11); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.1f ns to transfer money with a one global lock.%n", (double) time / accountCount); - } - } - - private static void transfer(Object lock, Account from, Account to, int amount) { - synchronized (lock) { - if (from.balance() < amount) throw new IllegalArgumentException(); - from.transfer(-amount); - to.transfer(amount); - } - } - - - static class Account implements Comparable { - private static final AtomicLong IDS = new AtomicLong(); - private final long id = IDS.getAndIncrement(); - private final Lock lock = new ReentrantLock(); - private long balance; - - public Account(long balance) { - this.balance = balance; - } - - public Lock lock() { - return lock; - } - - public long balance() { - return balance; - } - - public void transfer(long delta) { - if (delta + balance < 0) throw new IllegalStateException(); - balance += delta; - } - - @Override - public int compareTo(Account o) { - return id > o.id ? +1 : -1; - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/ThreadedFibonacciMain.java b/src/test/java/com/google/code/java/core/threads/ThreadedFibonacciMain.java deleted file mode 100644 index 5f565a4..0000000 --- a/src/test/java/com/google/code/java/core/threads/ThreadedFibonacciMain.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.google.code.java.core.threads; - -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; - -/** - * @author peter.lawrey - */ -public class ThreadedFibonacciMain { - static final ExecutorService es = Executors.newCachedThreadPool(); - - public static void main(String... args) { - for (int i = 2; i <= 30; i++) { - long start = System.nanoTime(); - long n = concurrentFibonacci(i); - long time = System.nanoTime() - start; - System.out.printf("Fibonacci %,d was %,d, took %,d us, Time ratio=%.1f %n", i, n, time / 1000, time / 1000.0 / n); - } - es.shutdown(); - } - - public static long concurrentFibonacci(int num) { - Future ret = es.submit(new FibonacciCallable(num)); - return get(ret); - } - - static long get(Future ret) { - try { - return ret.get(); - } catch (Exception e) { - throw new AssertionError(e); - } - } - - static class FibonacciCallable implements Callable { - private final int num; - - public FibonacciCallable(int num) { - this.num = num; - } - - @Override - public Long call() throws Exception { - if (num < 2) return 1L; - Future ret = es.submit(new FibonacciCallable(num - 2)); - // call using the current thread. - long num1 = new FibonacciCallable(num - 1).call(); - return get(ret) + num1; - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/UnthreadedAccountMain.java b/src/test/java/com/google/code/java/core/threads/UnthreadedAccountMain.java deleted file mode 100644 index 3c44360..0000000 --- a/src/test/java/com/google/code/java/core/threads/UnthreadedAccountMain.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.google.code.java.core.threads; - -import java.util.concurrent.atomic.AtomicLong; - -/** - * @author peter.lawrey - */ -public class UnthreadedAccountMain { - public static void main(String... args) { - int accountCount = 20 * 1000; - Account[] accounts = new Account[accountCount]; - for (int i = 0; i < accounts.length; i++) accounts[i] = new Account(100); - for (int r = 0; r < 9; r++) { - long start = System.nanoTime(); - for (int i = 0; i < accountCount; i += 2) { - transfer(accounts[i], accounts[i + 1], 10); - transfer(accounts[i + 1], accounts[i], 11); - } - long time = System.nanoTime() - start; - System.out.printf("Took an average of %.1f ns to transfer money, single threaded%n", (double) time / accountCount); - } - } - - private static void transfer(Account from, Account to, int amount) { - if (from.balance() < amount) throw new IllegalArgumentException(); - from.transfer(-amount); - to.transfer(amount); - } - - - static class Account implements Comparable { - private static final AtomicLong IDS = new AtomicLong(); - private final long id = IDS.getAndIncrement(); - - private long balance; - - public Account(long balance) { - this.balance = balance; - } - - public long balance() { - return balance; - } - - public void transfer(long delta) { - if (delta + balance < 0) throw new IllegalStateException(); - balance += delta; - } - - @Override - public int compareTo(Account o) { - return id > o.id ? +1 : -1; - } - } -} diff --git a/src/test/java/com/google/code/java/core/threads/UnthreadedFibonacciMain.java b/src/test/java/com/google/code/java/core/threads/UnthreadedFibonacciMain.java deleted file mode 100644 index b42c616..0000000 --- a/src/test/java/com/google/code/java/core/threads/UnthreadedFibonacciMain.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.google.code.java.core.threads; - -/** - * @author peter.lawrey - */ -public class UnthreadedFibonacciMain { - public static void main(String... args) { - for (int i = 2; i <= 91; i++) { - long start = System.nanoTime(); - long n = -1; -// for(int j=0;j<100;j++) - n = serialFibonacci(i); - long time = System.nanoTime() - start; - System.out.printf("Fibonacci %,d was %,d, took %,d us%n", i, n, time / 1000); - } - } - - public static long serialFibonacci(int num) { - long a = 1; - long b = 1; - while (num-- >= 2) { - long c = a + b; - a = b; - b = c; - } - return b; - } -} diff --git a/src/test/java/com/google/code/java/core/time/HiresTimerTest.java b/src/test/java/com/google/code/java/core/time/HiresTimerTest.java deleted file mode 100644 index b171e1c..0000000 --- a/src/test/java/com/google/code/java/core/time/HiresTimerTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.google.code.java.core.time;/* - Copyright 2011 Peter Lawrey - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - */ - -import org.junit.Test; - -import static junit.framework.Assert.assertEquals; - -public class HiresTimerTest { - @Test - public void testCurrentTimeUS() throws Exception { - int count = 0; - for (int i = 0; i < 100; i++) { - final long timeUS = HiresTimer.currentTimeUS(); - System.out.println(HiresTimer.toString(timeUS)); - if (timeUS % 1000 == 0) - count++; - } - assertEquals(1, count, 1); - } - - @Test - public void testToString() throws Exception { - String[] expected = ("1970/01/01T00:00:00.000001\n" + - "1970/01/01T00:00:00.000010\n" + - "1970/01/01T00:00:00.000100\n" + - "1970/01/01T00:00:00.001000\n" + - "1970/01/01T00:00:00.010000\n" + - "1970/01/01T00:00:00.100000\n" + - "1970/01/01T00:00:01.000000\n" + - "1970/01/01T00:00:10.000000\n" + - "1970/01/01T00:01:40.000000\n" + - "1970/01/01T00:16:40.000000\n" + - "1970/01/01T02:46:40.000000\n" + - "1970/01/02T03:46:40.000000\n" + - "1970/01/12T13:46:40.000000\n" + - "1970/04/26T17:46:40.000000\n" + - "1973/03/03T09:46:40.000000\n" + - "2001/09/09T01:46:40.000000\n" + - "2286/11/20T17:46:40.000000").split("\n"); - int n = 0; - for (long i = 1; i < 1e17; i *= 10) - assertEquals(expected[n++], HiresTimer.toString(i)); - } -}