I am calling two C++ functions from C#. While doing that in a iteration for around 1 million call i am seeing a overhead of about 30%.
C++ function :
EXTERN_C void STDAPICALLTYPE FunctionA(UINT_PTR mathId)
{
...
...
}
In my C# assembly dll as :
[DllImport("CPlusPlus.dll")]
public static extern void FunctionA([In] IntPtr mathID);
Called from function as below:
public static void HelpingFunction([In]UInt64 mathID)
{
FunctionA((IntPtr)mathID);
}
This way of implementation is creating more overhead when the "HelpingFunction" is called more than a million times.
Can someone give me other ideas so that the overhead can be reduced? What are the other ways to call a C++ function from a C# assembly?
This can become overhead if the execution time of function is less than the switching time from the caller function to called function (callee). For functions that are large and/or perform complex tasks, the overhead of the function call is usually insignificant compared to the amount of time the function takes to run.
Memory overhead is at a minimum when you use functions because you do not duplicate code; inlined code is duplicated into the call site. Performance overhead these days is negligible because modern architectures are really good predicting and calling with about 1-2 cycle overhead only.
There is not much overhead at all, especially with small (inline-able) functions or even classes.
Overhead refers to the ongoing business expenses not directly attributed to creating a product or service. It is important for budgeting purposes but also for determining how much a company must charge for its products or services to make a profit.
You can try to add SuppressUnmanagedCodeSecurityAttribute
.
Allows managed code to call into unmanaged code without a stack walk.
https://msdn.microsoft.com/en-us/library/system.security.suppressunmanagedcodesecurityattribute.aspx
But on p/invoke call always will be fixed cost overhead:
PInvoke has an overhead of between 10 and 30 x86 instructions per call. In addition to this fixed cost, marshaling creates additional overhead. There is no marshaling cost between blittable types that have the same representation in managed and unmanaged code. For example, there is no cost to translate between int and Int32.
https://msdn.microsoft.com/en-us/library/ms235282.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With