Created
December 5, 2021 17:12
-
-
Save apangin/7cc117a8cd0293575bae3a7fea5abeef to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <jni.h> | |
#include <string.h> | |
static inline jlong vectorized_cmp(const jlong* s1, const jlong* s2, int size) { | |
jlong result = 0; | |
for (int i = 0; i < size; i++) { | |
result |= s1[i] ^ s2[i]; | |
} | |
return result; | |
} | |
JNIEXPORT jboolean JavaCritical_bench_LongArrayCompare_compare(jint a_len, jlong* a_raw, | |
jint b_len, jlong* b_raw, | |
jint size) { | |
#define STEP 64 | |
while (size >= STEP) { | |
if (vectorized_cmp(a_raw, b_raw, STEP) != 0) { | |
return JNI_FALSE; | |
} | |
a_raw += STEP; | |
b_raw += STEP; | |
size -= STEP; | |
} | |
#undef STEP | |
return vectorized_cmp(a_raw, b_raw, size) == 0 ? JNI_TRUE : JNI_FALSE; | |
} | |
JNIEXPORT jboolean Java_bench_LongArrayCompare_compare(JNIEnv* env, jobject unused, | |
jlongArray a, jbyteArray b, jint size) { | |
void* a_raw = (*env)->GetPrimitiveArrayCritical(env, a, NULL); | |
void* b_raw = (*env)->GetPrimitiveArrayCritical(env, b, NULL); | |
jboolean result = JavaCritical_bench_LongArrayCompare_compare(0, a_raw, 0, b_raw, size); | |
(*env)->ReleasePrimitiveArrayCritical(env, b, b_raw, JNI_ABORT); | |
(*env)->ReleasePrimitiveArrayCritical(env, a, a_raw, JNI_ABORT); | |
return result; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package bench; | |
import org.openjdk.jmh.annotations.Benchmark; | |
import org.openjdk.jmh.annotations.Param; | |
import org.openjdk.jmh.annotations.Scope; | |
import org.openjdk.jmh.annotations.Setup; | |
import org.openjdk.jmh.annotations.State; | |
import java.util.Arrays; | |
import java.util.concurrent.ThreadLocalRandom; | |
@State(Scope.Benchmark) | |
public class LongArrayCompare { | |
@Param({"10", "100", "1000"}) | |
private int size; | |
private long[] a; | |
private long[] b; | |
@Setup | |
public void setup() { | |
a = ThreadLocalRandom.current().longs(size).toArray(); | |
b = a.clone(); | |
b[b.length - 1]++; | |
} | |
@Benchmark | |
public boolean arraysEquals() { | |
return Arrays.equals(a, b); | |
} | |
@Benchmark | |
public boolean jniCritical() { | |
return a.length == b.length && compare(a, b, a.length); | |
} | |
private static native boolean compare(long[] a, long[] b, int size); | |
static { | |
System.loadLibrary("arraycmp"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment