Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1997. C# - nano 시간을 가져오는 방법 [링크 복사], [링크+제목 복사]
조회: 6995
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

C# - nano 시간을 가져오는 방법

윈도우에서 nano 시간을 어떻게 가져올 수 있을까요? 윈도우 환경의 Java에서 System.nanoTime을 호출해 보면,

public class Main {
    public static void main(String[] args) {
        long nanoTime1 = java.lang.System.nanoTime();
        long nanoTime2 = java.lang.System.nanoTime();
        long nanoTime3 = java.lang.System.nanoTime();
        long nanoTime4 = java.lang.System.nanoTime();
        long nanoTime5 = java.lang.System.nanoTime();

        System.out.println(nanoTime1);
        System.out.println(nanoTime2);
        System.out.println(nanoTime3);
        System.out.println(nanoTime4);
        System.out.println(nanoTime5);
    }
}

/* 출력 결과
1829807260513100
1829807260513200
1829807260513200
1829807260513300
1829807260513300
*/

빠르게 호출하다 보니 연이어 나오기도 하지만 무엇보다도 100 이하의 숫자는 0인 것이 특징입니다. 즉, 그 이하로는 값을 구할 수 없다는 것인데, nanoTime 메서드의 의미를 상기해 보면 결국 100나노초 이하의 값은 구할 수 없는 것입니다.

오호... 100나노초라... 익숙한 숫자죠? ^^ 바로 전에 언급했던 글에 그 이유가 있습니다.

Windows 10부터 바뀐 QueryPerformanceFrequency, QueryPerformanceCounter
; https://www.sysnet.pe.kr/2/0/13035

자, 그렇다면 닷넷에서는 어떻게 해야 할까요? 검색해 보면 다음의 글이 나옵니다.

What is the equivalent to System.nanoTime() in .NET?
; https://stackoverflow.com/questions/1551742/what-is-the-equivalent-to-system-nanotime-in-net

위의 답변에 보면 C# 코드가 나오는데요, 이를 이용해 위의 자바 예제처럼 닷넷 코드로 구성해 실행하면,

using System.Diagnostics;

internal class Program
{
    static void Main(string[] args)
    {
        long nano1 = Stopwatch.GetTimestamp() * 100L;
        long nano2 = Stopwatch.GetTimestamp() * 100L;
        long nano3 = Stopwatch.GetTimestamp() * 100L;
        long nano4 = Stopwatch.GetTimestamp() * 100L;
        long nano5 = Stopwatch.GetTimestamp() * 100L;

        Console.WriteLine(nano1);
        Console.WriteLine(nano2);
        Console.WriteLine(nano3);
        Console.WriteLine(nano4);
        Console.WriteLine(nano5);
    }
}
/* 출력 결과
1830258684212100
1830258684212100
1830258684212100
1830258684212200
1830258684212200
*/

위와 같이 나옵니다. 근래의 윈도우 운영체제에서 GetTimestamp 값은 QueryPerformanceCounter를 이용한 값과 동일한데요, 그래서 다음과 같은 식으로 구하는 것도 가능합니다.

using System;
using System.Runtime.InteropServices;

internal class Program
{
    [DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

    static void Main(string[] args)
    {
        long time1 = 0;
        long time2 = 0;
        long time3 = 0;
        long time4 = 0;
        long time5 = 0;

        QueryPerformanceCounter(out time1);
        QueryPerformanceCounter(out time2);
        QueryPerformanceCounter(out time3);
        QueryPerformanceCounter(out time4);
        QueryPerformanceCounter(out time5);

        Console.WriteLine(time1 * 100L);
        Console.WriteLine(time2 * 100L);
        Console.WriteLine(time3 * 100L);
        Console.WriteLine(time4 * 100L);
        Console.WriteLine(time5 * 100L);
    }
}

/* 출력 결과
1830948394699000
1830948394699100
1830948394699100
1830948394699100
1830948394699200
*/

(지난 글에 설명한 이유로) 근래에는 QueryPerformanceFrequency 호출 없이도 다음과 같이 GetTimestamp로부터 단순히 10의 n 승에 해당하는 값만으로 다른 시간 단위로의 변환을 자유롭게 할 수 있습니다.

long time1 = Stopwatch.GetTimestamp();

long nanoSeconds = time1 * 100; // 나노초
long microSeonds = time1 / 10;  // 마이크로초
long milliSeconds = time1 / TimeSpan.TicksPerMillisecond; // 밀리초
long seconds = time1 / TimeSpan.TicksPerSecond; // 초




물론, 그 이상 정밀도를 높이려면 CPU에서 제공하는 tsc를 읽어내는 것도 한 방법입니다. 이전 글에서 설명한 대로,

윈도우 운영체제의 시간 함수 (4) - RTC, TSC, PM Clock, HPET Timer
; https://www.sysnet.pe.kr/2/0/11067#tsc

윈도우 운영체제의 시간 함수 (5) - TSC(Time Stamp Counter)와 QueryPerformanceCounter
; https://www.sysnet.pe.kr/2/0/11068

GHz 사이클 수에 따른 계산이므로, 만약 3.4GHz CPU라면 1 / 3,400,000,000 == 0.0000000002941...초가 나옵니다. 따라서 0.0000002941밀리초, 0.0002941마이크로초, 0.2941나노초가 되어 tsc 숫자 1이 변화하면 0.2941나노초가 지났다는 의미가 됩니다.

아쉽지만, 이 방법은 C#에서는 제공하는 방법이 없으므로 사용하려면 C로 DLL을 만들어 연결해야 합니다. (혹은, 간단한 기계어이므로 cpuid 방식처럼 만들어 호출하는 것은 가능합니다.)




참고로, Stopwatch의 도움말을 보면 이런 설명들이 나옵니다.

The timer used by the Stopwatch class depends on the system hardware and operating system. IsHighResolution is true if the Stopwatch timer is based on a high-resolution performance counter. Otherwise, IsHighResolution is false, which indicates that the Stopwatch timer is based on the system timer.


A pointer to a variable that receives the current performance-counter frequency, in counts per second. If the installed hardware doesn't support a high-resolution performance counter, this parameter can be zero (this will not occur on systems that run Windows XP or later).


On systems that run Windows XP or later, the function will always succeed and will thus never return zero.


그러니까, 이제는 그냥 무시해도 좋은 설명입니다. 즉, 현재는 (Windows XP 이후이므로) 대부분의 컴퓨터에서 Stopwatch.IsHighResolution의 값은 True가 반환될 것이며 따라서 DateTime.Ticks를 반환하는 경우는 없다고 봐도 좋을 것입니다.




그렇긴 한데, 여전히 좀 걸리는군요. 과연 Windows 10뿐만 아니라 현재의 Windows XP 이후의 모든 운영체제에서는 QueryPerformanceFrequency == 10,000,000 값이 고정적으로 나올까요? 혹시나 여러분들의 PC에서 다음의 소스 코드를 실행했을 때,

using System.Diagnostics;
using System.Runtime.InteropServices;

internal class Program
{
    [DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

    [DllImport("Kernel32.dll")]
    static extern bool QueryPerformanceFrequency(out long ticksPerSecond);

    static void Main(string[] args)
    {
        QueryPerformanceFrequency(out long value);
        Console.WriteLine(value);

        {
            long nano1 = Stopwatch.GetTimestamp() * 100L;
            Console.WriteLine(nano1);
        }
        {

            long time1 = 0;
            QueryPerformanceCounter(out time1);
            Console.WriteLine(time1 * 100L);
        }
    }
}

/* 출력 결과
10000000
1838876675286800
1838876675452100
*/

저렇게 첫 번째 줄이 10000000 값이 아니거나, 또는 두 번째와 세 번째의 출력값이 현저하게 다른 경우가 있다면 제보 부탁드리겠습니다. ^^




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/4/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-04-26 06시04분
[kernel] 마지막예제에서 QueryPerformanceFrequency 호출 코드가 빠졌네요 ^^;
[guest]
2022-04-27 09시21분
@kernel ^^ 반영했습니다.
정성태

... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12429정성태11/25/20209952디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/20208872VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202010016.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208642오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209661VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202010069VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202011017.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208817.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208545.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207734오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/20208933VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202011023오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/20208436오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/20209689오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/20209727.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202010801VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202010480.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202012781.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/20209742오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/20209707디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202011106.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202022362도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202011362.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202012938.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202010436.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202010935.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
... 46  47  [48]  49  50  51  52  53  54  55  56  57  58  59  60  ...