4

I was reading What makes JNI calls slow? and I was wondering if Python's C interface is any better than JNI.

I heard that if you want to make certain parts of your python programs faster, or if a certain part of the program was really hurting your program's performance, you write them in C, and make Python call them.

Does the C interface it incur the same costs JNI does? why or why not?

4
  • The CPython implementation is written in C. It should be obvious that CPython with C extensions would be really efficient. Does that answer your question? What more do you need to know?
    – S.Lott
    Dec 22, 2011 at 3:00
  • 1
    @S.Lott, being written in C does not automatically make it faster. stackoverflow.com/questions/2591879/…
    – Job
    Dec 22, 2011 at 4:23
  • 1
    @Job "make it faster" != "really efficient" (sometimes, but not always)
    – yannis
    Dec 22, 2011 at 7:50
  • Um. The question was about overheads between JNI and C, right? Less overhead would be faster, right? I'm unclear what hair is being split in the comments. I can't see how CPython + C could even raise a question. What more information is needed?
    – S.Lott
    Dec 22, 2011 at 11:38

1 Answer 1

7

Even though I don't know a direct answer to your question, I can't resist answering indirectly:

I heard that if you want to make certain parts of your python programs faster, or if a certain part of the program was really hurting your program's performance, you write them in C, and make Python call them.

As written in the topmost answer of the SO question you linked to, "slow" here means tens of nanoseconds. If your expensive part (written in C) takes even one microsecond to execute, then the proportional cost of the C/JNI interface is negligible. The cost only comes whenever you call the native part (and when the call returns), not while the native part is executing. If you keep the number of calls low, then the extra cost is low. That is, don't write tight Python loops that call C functions; do write the loop itself in C and call it from Python.

As another example that the JNI costs are usually negligible: many of JDK's core classes, e.g. most functions in Math, and ultimately all graphics and I/O functions map to JNI calls under the hood. Regardless, Java is usually considered to be way faster than CPython.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.