Recalling dllimport for C dll in C # seems slow compared to direct C #

I tested the speed of calling C code from dll in C # with System.Runtime.InteropServices.DllImportAttribute. Function C generates a custom structure, populates it with values, does, calculates, and then returns the result. I repeated this process hundreds of thousands of times in a loop in which I recorded the number of ticks before and after the loop. Then I did the same function in direct C # and repeated this test. The direct C # method was much faster than using an unmanaged DLL. What for? It seems that there is no inconvenience in speed from the uncontrollable.

c2cstest.c

#include <stdio.h>
struct test {
double a;
double b;
double c;
};
_declspec(dllexport) double myCfunction(double input) {
struct test one;
one.a = input;
one.b = one.a * one.a;
one.c = one.b * one.a;
return one.c;
}

cl / LD cscstest.c runCcode.cs

using System;
using System.Runtime.InteropServices;
class test
{
[DllImport("c2cstest.dll")]
public static extern double myCfunction (double input);
static void Main()
{
double x = 5.25;
double result = 0.0;
long tick1 = DateTime.Now.Ticks;
for(int y = 100000; y > 0; y--)
{
result = myCfunction(x);
}
long tick2 = DateTime.Now.Ticks;
Console.WriteLine("Answer is {0}.  Dllimport took {1} ticks.", result, tick2-tick1);
}
}

OUTPUT: Reply 144.703125. Dllimport took 250,000 ticks. RunCScode.cs

using System;
using System.Runtime.InteropServices;
struct test
{
public double a;
public double b;
public double c;
}
class testclass
{
double Mycsfunction (double input)
{
test one;
one.a = input;
one.b = one.a * one.a;
one.c = one.b * one.a;
return one.c;
}
static void Main()
{
double x = 5.25;
double result = 0.0;
testclass ex = new testclass();
long tick1 = DateTime.Now.Ticks;
for(int y = 100000; y > 0; y--)
{
result = ex.Mycsfunction(x);
}
long tick2 = DateTime.Now.Ticks;
Console.WriteLine("Answer is {0}.  Straight CS took {1} ticks.", result, tick2-tick1);
}}

OUTPUT: Reply 144.703125. Straight CS has taken 50,000 ticks.

: , " " , , .

: ( ). . . , , - .

+3
1

, ; -, . -, , , , # - - (, , ) , , .

runCScode.cs :

c:\temp>csc runCScode.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


c:\temp>runCScode
Answer is 144.703125.  Straight CS took 10001 ticks.

for :

c:\temp>csc runCScode.noloop.cs
Microsoft (R) Visual C# 2010 Compiler version 4.0.30319.1
Copyright (C) Microsoft Corporation. All rights reserved.


c:\temp>runCScode.noloop
Answer is 144.703125.  Straight CS took 10001 ticks.

, , , , - - , DateTime ( , ), ). , , - , , , result. , tick1 :

tick1 = DateTime.Now.Ticks;

, - tick1 DateTime.Now.Ticks.

:

c:\temp>runCScode.noloop
Answer is 144.703125.  Straight CS took 0 ticks.

(: , , , tick1, 0. 10000 +/- 1. , tick1, 0 ).

, , , C , # , , C, , P/Invoke / . . , , , , C .NET, , , , -, C ++ , # ( ++/CLI).

.

, , , C ++ DLL . , ( API), DLL, , .NET-.

+2

All Articles