Skip to content

Instantly share code, notes, and snippets.

@nojima
Created June 14, 2017 15:30
Show Gist options
  • Save nojima/e3e62b8975a1c34b0c5478f66b9fc2f8 to your computer and use it in GitHub Desktop.
Save nojima/e3e62b8975a1c34b0c5478f66b9fc2f8 to your computer and use it in GitHub Desktop.
JNA を使って Java から getrusage() を呼び出すサンプル
package com.ynojima.utilization;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Structure;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary)Native.loadLibrary("c", CLibrary.class);
int syscall(int number);
int getrusage(int who, rusage usage);
}
public static class timeval extends Structure {
public long tv_sec;
public int tv_usec;
@Override
protected List getFieldOrder() {
return Arrays.asList("tv_sec", "tv_usec");
}
@Override
public String toString() {
return String.format("%d.%06d", tv_sec, tv_usec);
}
}
public static class rusage extends Structure {
public timeval ru_utime;
public timeval ru_stime;
public long ru_maxrss;
public long ru_ixrss;
public long ru_idrss;
public long ru_isrss;
public long ru_minflt;
public long ru_majflt;
public long ru_nswap;
public long ru_inblock;
public long ru_oublock;
public long ru_msgsnd;
public long ru_msgrcv;
public long ru_nsignals;
public long ru_nvcsw;
public long ru_nivcsw;
@Override
protected List getFieldOrder() {
return Arrays.asList(
"ru_utime",
"ru_stime",
"ru_maxrss",
"ru_ixrss",
"ru_idrss",
"ru_isrss",
"ru_minflt",
"ru_majflt",
"ru_nswap",
"ru_inblock",
"ru_oublock",
"ru_msgsnd",
"ru_msgrcv",
"ru_nsignals",
"ru_nvcsw",
"ru_nivcsw");
}
}
// wrapper function of gettid()
private static int gettid() {
final int SYS_gettid = 186;
return CLibrary.INSTANCE.syscall(SYS_gettid);
}
// wrapper function of getrusage()
private static rusage getrusage() {
final int RUSAGE_THREAD = 1;
rusage usage = new rusage();
CLibrary.INSTANCE.getrusage(RUSAGE_THREAD, usage);
return usage;
}
// --- 試しに動かしてみる ---
private static class HelloRunnable implements Runnable {
private final int index;
HelloRunnable(int i) {
index = i;
}
public void run() {
long x = 0;
for (long i = 0; i < 1000000000L * index; ++i) {
x += i;
}
int tid = gettid();
rusage usage = getrusage();
System.err.println("[" + tid + "] ru_utime=" + usage.ru_utime + " ru_stime=" + usage.ru_stime + " x=" + x);
}
}
public static void main(String[] args) throws Exception {
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; ++i)
threads.add(new Thread(new HelloRunnable(i)));
for (Thread t : threads)
t.start();
for (Thread t : threads)
t.join();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment