성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] Detecting blocking calls using asyn...
[정성태] 아쉽게도, 커뮤니티는 아니고 개인 블로그입니다. ^^
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
[정성태] 만드실 수 있습니다. 단지, Unity 엔진 내의 스크립트와 W...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>calli IL 호출이 DllImport 호출보다 빠를까요?</h1> <p> 네이티브 함수를 닷넷에서 직접 호출할 수 있는 IL 코드가 바로 calli인데요.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > OpCodes.Calli Field ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.calli'>https://learn.microsoft.com/en-us/dotnet/api/system.reflection.emit.opcodes.calli</a> </pre> <br /> 예전에 OpenCover 코드 커버리지 도구를 살펴보면서 calli에 대한 동작 방식을 설명한 적도 있습니다. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > OpenCover 코드 커버리지 도구의 동작방식을 통해 살펴보는 Calli IL 코드 사용법 ; <a target='tab' href='http://www.sysnet.pe.kr/2/0/2882'>http://www.sysnet.pe.kr/2/0/2882</a> </pre> <br /> 근데... 이것이 일반적인 delegate 호출보다 성능이 더 좋다고 합니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Why is Calli Faster Than a Delegate Call? ; <a target='tab' href='http://stackoverflow.com/questions/5893024/why-is-calli-faster-than-a-delegate-call'>http://stackoverflow.com/questions/5893024/why-is-calli-faster-than-a-delegate-call</a> </pre> <br /> 덧글에 보면 "The EmitCalli is faster because it is a raw byte code call"라고 하는데, 그럼 혹시 "<a target='tab' href='https://github.com/dotnet/runtime/blob/main/docs/design/coreclr/botr/corelib.md#calling-from-managed-to-native-code'>Managed to Unmanaged"간의 전환</a>이 좀 더 가벼울 수도 있지 않을까요?<br /> <br /> <hr style='width: 50%' /><br /> <br /> 그래서, 가정을 해봤습니다. .NET에서 native 코드 호출 방법이 대표적으로 DllImport가 있는데요. 그것과 비교해 보면 어떨까요? 예제를 간단히 하기 위해 <a target='tab' href='https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getcurrentthreadid'>GetCurrentThreadId</a> Win32 API를 대상으로 다음의 3가지 방법에 대해 각각 성능 테스트를 해봤습니다.<br /> <br /> <ol> <li>C++ DLL 프로젝트에서 GetCurrentThreadId Win32 API의 주소를 반환해 calli로 호출하는 예제</li> <li>BCL에서 제공되는 AppDomain.GetCurrentThreadId를 호출하는 예제</li> <li>DllImport로 직접 kernel32.dll의 GetCurrentThreadId를 호출하는 예제</li> </ol> <br /> 소스 코드는 대충 다음과 같습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ============== C++ DLL ============== WIN32PROJECT1_API __int64 __stdcall fnWin32Project1() { return (__int64)&::GetCurrentThreadId; } </pre> <br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ============== C# DLL ============== using System; using System.Reflection.Emit; using System.Runtime.InteropServices; namespace ClassLibrary1 { [System.Security.SecuritySafeCritical] public class Class1 { [DllImport("Win32Project1.dll", EntryPoint = "fnWin32Project1")] static extern long GetThisThreadId32(); static GetThisThreadIdDelegate _GetThisThreadIdMethod = null; delegate int GetThisThreadIdDelegate(); static Class1() { long result = 0; if (_GetThisThreadIdMethod == null) { if (IntPtr.Size == 4) { result = GetThisThreadId32(); } var type = typeof(Class1); DynamicMethod dynamicMethod = new DynamicMethod("", typeof(int), Type.EmptyTypes, type, true); var iLGenerator = dynamicMethod.GetILGenerator(); if (IntPtr.Size == 4) { iLGenerator.Emit(OpCodes.Ldc_I4, (int)result); } else { iLGenerator.Emit(OpCodes.Ldc_I8, result); } iLGenerator.EmitCalli(OpCodes.Calli, CallingConvention.StdCall, typeof(int), Type.EmptyTypes); iLGenerator.Emit(OpCodes.Ret); GetThisThreadIdDelegate tempDelegate = dynamicMethod.CreateDelegate(typeof(GetThisThreadIdDelegate)) as GetThisThreadIdDelegate; _GetThisThreadIdMethod = tempDelegate; } } [System.Security.SecuritySafeCritical] public static int GetThisThreadId() { try { return _GetThisThreadIdMethod(); } catch { } return 0; } } } </pre> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // ============== C# EXE ============== using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace ConsoleApplication1 { class Program { [DllImport("kernel32.dll")] static extern int GetCurrentThreadId(); static void Main(string[] args) { Action<int, string, Func<int>> action = (loopCount, title, work) => { Stopwatch st = new Stopwatch(); st.Start(); Random rand = new Random(Environment.TickCount); for (int i = 0; i < loopCount; i++) { work(); } st.Stop(); Console.WriteLine(title + " : " + st.ElapsedTicks); }; action(1, "touch-JIT", ClassLibrary1.Class1.GetThisThreadId); action(1, "touch-JIT", AppDomain.GetCurrentThreadId); // <a target='tab' href='https://www.sysnet.pe.kr/2/0/13024'>이 코드는 닷넷 프레임워크 환경에서 테스트한 것입니다. (참고: 닷넷 런타임에 따라 달라지는 AppDomain.GetCurrentThreadId의 반환값)</a> action(1, "touch-JIT", GetCurrentThreadId); Console.WriteLine(); action(10000, "Calli", ClassLibrary1.Class1.GetThisThreadId); action(10000, "BCL", AppDomain.GetCurrentThreadId); action(10000, "DllImport", GetCurrentThreadId); } } } </pre> <br /> 결과는 Calli가 코드가 복잡한 거에 비하면 감동적인 수준은 아니지만 그래도 빨라지긴 했습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > // x86 Release 빌드로 테스트 (낮을수록 좋음) Calli : 851 BCL : 2170 DllImport : 1260 Calli : 843 BCL : 1303 DllImport : 1577 Calli : 881 BCL : 1445 DllImport : 1247 </pre> <br /> (<a target='tab' href='http://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=932&boardid=331301885'>첨부한 파일은 위의 코드 테스트를 포함</a>합니다.)<br /> <hr style='width: 50%' /><br /> <br /> 결론은, 성능을 조금이라도 개선할 필요가 있을 때만 calli 호출을 쓰시고 그 외에는 그냥 DllImport를 쓰시는 것이 좋습니다. 또는, 특수한 사례로 네이티브 코드를 제공할 때 symbol export가 안되도록 숨기고 싶은 경우에 한해 calli를 쓰는 것도 좋겠고. ^^<br /> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
5953
(왼쪽의 숫자를 입력해야 합니다.)