Optimizing C++ call from C#

254 views Asked by At

I am calling a two C++ function calls from C# my code is below.

[DllImport("A.dll", CallingConvention = CallingConvention.StdCall, EntryPoint = "FuncA"), System.Security.SuppressUnmanagedCodeSecurity]
    public static extern void FuncA(UInt64 functionID);

In C++ code is :

EXTERN_C void STDMETHODCALLTYPE FuncA(UINT_PTR functionId)
{
    return;
}

This function is being called from C# to C++ for about 2 million times. Without this function call my web request is getting completed in 5.9 seconds.. And with this function call i am getting 7.1 seconds..

Approx 15% overhead. Already i have used "SuppressUnmanagedCodeSecurity" by seeing a post, which reduced the overhead from 30% to 15 % .. But is there any other way to reducing this 15% overhead.??

Update1:

The function ID needs to be sent to C++ for each and every function calls of C#. The C++ function is not an empty function. It needs to store the function IDs in a STL and another thread will process it. I am doing a .NET profiler sort of thing. I need to profile each and every function calls . This FuncA C++ function will get called from injected helper functions.

Thanks,

./Rahul

2

There are 2 answers

0
Melvin On

What does the C++ function do? Is it really an empty method? Is it a necessary step in your chain of actions to perform?

Perhaps it is faster to rewrite this method to C#, to incorporate it in the workflow there, without having to invoke external (probably unsafe) methods.

If the action being performed by the C++ code has nothing to do with the rest of your flow, perhaps you might win some time by having it run in a background worker, or a separate thread, so your C# code doesn't have to wait for the code to run. I suppose this might be a valid option, since your method returns void.

Perhaps a little more information about why and how might help us to find a better suited answer.

1
fatihk On

As a longshot you can create a managed C++ CLI static library which calls the unmanaged C++ functions with lower performance decrease and add as reference to the C++/CLI library in your C# project. The C# application can then make managed method calls to the C++ CLI library linked, which in turn can make unmanaged method calls. Although this results in some indirection, it may provide some performance increase.