1

I'm looking at using ashmem to help a couple processes coordinate. Before I start spending the effort to use it, I thought I'd see how much of a speedup it offers over a plain 'ol file.

    try {

        Random random = new Random(System.currentTimeMillis());

        byte[] buf = new byte[4096];
        random.nextBytes(buf);

        MemoryFile memfil = new MemoryFile("testmem", LENGTH);

        long start = System.nanoTime();
        OutputStream memOs = memfil.getOutputStream();
        memOs.write(buf);
        Log.e(TAG, "Ashmem   writes took " + (System.nanoTime()-start));
        memfil.close();

        OutputStream fos = new FileOutputStream(new File(this.getFilesDir(), "testfil"));
        start = System.nanoTime();
        fos.write(buf);
        fos.flush();
        Log.e(TAG, "File     writes took " + (System.nanoTime() - start));
        fos.close();
    } catch (IOException e) {
        Log.e(TAG, "Failed to open ashmem: ", e);
    }

Here are some typical numbers

07-30 20:49:01.742    2994-2994/? E/AshmemTestActivity﹕ Ashmem   writes took 214531
07-30 20:49:01.742    2994-2994/? E/AshmemTestActivity﹕ File     writes took 68541

The numbers don't get much better even when I include the time to close the file. How could memory writes be slower than a file on disk? What am I doing wrong?

James Koppel
  • 1,587
  • 1
  • 10
  • 16
  • 1
    Does ashmem use "RAM" or "memory mapped files"? – Elliott Jul 31 '15 at 18:40
  • Here's the description from the Confectioner's Guide: "Anonymous Shared Memory (ASHMem): A mechanism to allow shared memory. Applications can open a character device (/dev/ashmem) and created a memory region which can then be mapped into memory. This is require to work around the restriction of no world-writable directories and System V IPC." Sounds like RAM. – James Koppel Aug 03 '15 at 18:07
  • 1
    These are both really fast (< 1 ms)--I think people generally worry about disk operations on spinning disks where even seeking to a file can take like 10 ms, but Android devices use SSDs, right? Also, it might be the case that the first time you use Ashmem it causes a page fault, which can add quite a bit of overhead. What happens to the measurements if you do repeated writes (this might amortize the cost of the page fault, if that's indeed what's happening)? – Elliott Aug 04 '15 at 04:14
  • I saw similar results when I did repeated writes. – James Koppel Aug 05 '15 at 00:02
  • It does indeed appear that virtually all the cost is in the first write, for both files and ashmem. They are about equal when I exclude the first write, but I am seeing ashmem take slightly longer. – James Koppel Aug 05 '15 at 00:02

0 Answers0