benchmark:Measure vsock host to VM transfer rate
Bug: 236123069
Bug: 244408006
Test: atest MicrodroidBenchmarks
Change-Id: I3731c7134efa6b0fddc24dc11b4e7a813f679be1
diff --git a/tests/benchmark/src/jni/Android.bp b/tests/benchmark/src/jni/Android.bp
new file mode 100644
index 0000000..e1bc8b0
--- /dev/null
+++ b/tests/benchmark/src/jni/Android.bp
@@ -0,0 +1,10 @@
+package{
+ default_applicable_licenses : ["Android-Apache-2.0"],
+}
+
+cc_library_shared {
+ name: "libiovsock_host_jni",
+ srcs: [ "io_vsock_host_jni.cpp" ],
+ header_libs: ["jni_headers"],
+ shared_libs: ["libbase"],
+}
\ No newline at end of file
diff --git a/tests/benchmark/src/jni/io_vsock_host_jni.cpp b/tests/benchmark/src/jni/io_vsock_host_jni.cpp
new file mode 100644
index 0000000..7f3d655
--- /dev/null
+++ b/tests/benchmark/src/jni/io_vsock_host_jni.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * 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.
+ */
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <android-base/result.h>
+#include <jni.h>
+#include <time.h>
+
+using android::base::Error;
+using android::base::Result;
+using android::base::WriteStringToFd;
+
+constexpr size_t kNumBytesPerMB = 1024 * 1024;
+
+Result<double> measure_send_rate(int fd, int num_bytes_to_send) {
+ std::string data;
+ data.assign(num_bytes_to_send, 'a');
+ clock_t start = clock();
+ if (!WriteStringToFd(data, fd)) {
+ return Error() << "Cannot send data to client";
+ }
+ clock_t end = clock();
+ double elapsed_seconds = (double)(end - start) / CLOCKS_PER_SEC;
+ LOG(INFO) << "Host:Finished sending data in " << elapsed_seconds << " seconds.";
+ double send_rate = num_bytes_to_send / kNumBytesPerMB / elapsed_seconds;
+ return {send_rate};
+}
+
+extern "C" JNIEXPORT jdouble JNICALL
+Java_com_android_microdroid_benchmark_IoVsockHostNative_measureSendRate(__unused JNIEnv *env,
+ __unused jclass clazz,
+ int fd,
+ int num_bytes_to_send) {
+ if (auto res = measure_send_rate(fd, num_bytes_to_send); res.ok()) {
+ return res.value();
+ } else {
+ LOG(ERROR) << "Cannot send data from host to VM: " << res.error();
+ abort();
+ }
+}