Skip to content

Instantly share code, notes, and snippets.

@sscdotopen
Created March 12, 2013 22:04
Show Gist options
  • Save sscdotopen/5147521 to your computer and use it in GitHub Desktop.
Save sscdotopen/5147521 to your computer and use it in GitHub Desktop.
import org.apache.mahout.math.DenseVector;
import org.apache.mahout.math.Vector;
import org.apache.mahout.math.function.IntObjectProcedure;
import org.apache.mahout.math.map.OpenIntObjectHashMap;
import java.util.Random;
public class Benchmark {
static int NUM_FEATURES = 20;
static Random RANDOM = new Random(0xdeadbeef);
public static void main(String[] args) {
int numItems = 2500000;
OpenIntObjectHashMap<Vector> M = new OpenIntObjectHashMap<Vector>(numItems);
for (int itemID = 0; itemID < numItems; itemID++) {
M.put(itemID, randomVector(NUM_FEATURES));
}
int numUsers = 50;
for (int n = 0; n < numUsers; n++) {
final Vector userFeatures = randomVector(NUM_FEATURES);
long start = System.currentTimeMillis();
M.forEachPair(new IntObjectProcedure<Vector>() {
@Override
public boolean apply(int itemID, Vector itemFeatures) {
userFeatures.dot(itemFeatures);
return true;
}
});
long pause = System.currentTimeMillis();
M.forEachPair(new IntObjectProcedure<Vector>() {
@Override
public boolean apply(int itemID, Vector itemFeatures) {
dot(userFeatures, itemFeatures);
return true;
}
});
long end = System.currentTimeMillis();
System.out.println("dot() " + (pause - start) + "ms, direct " + (end - pause) + "ms");
}
}
static double dot(Vector one, Vector two) {
double sum = 0;
for (int n = 0; n < NUM_FEATURES; n++) {
sum += one.getQuick(n) * two.getQuick(n);
}
return sum;
}
static Vector randomVector(int size) {
double[] values = new double[size];
for (int n = 0; n < size; n++) {
values[n] = RANDOM.nextDouble();
}
return new DenseVector(values, true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment