Microsoft MVP성태의 닷넷 이야기
.NET Framework: 1997. C# - nano 시간을 가져오는 방법 [링크 복사], [링크+제목 복사],
조회: 7290
글쓴 사람
정성태 (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 ^^ 반영했습니다.
정성태

... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...
NoWriterDateCnt.TitleFile(s)
11815정성태2/14/201911295오류 유형: 513. Visual Studio 2019 - VSIX 설치 시 "The extension cannot be installed to this product due to prerequisites that cannot be resolved." 오류 발생
11814정성태2/12/201910117오류 유형: 512. VM(가상 머신)의 NT 서비스들이 자동 시작되지 않는 문제
11813정성태2/12/201911703.NET Framework: 809. C# - ("Save File Dialog" 등의) 대화 창에 확장 속성을 보이는 방법
11812정성태2/11/20199573오류 유형: 511. Windows Server 2003 VM 부팅 후 로그인 시점에 0xC0000005 BSOD 발생
11811정성태2/11/201913321오류 유형: 510. 서버 운영체제에 NVIDIA GeForce Experience 실행 시 wlanapi.dll 누락 문제
11810정성태2/11/201911383.NET Framework: 808. .NET Profiler - GAC 모듈에서 GAC 비-등록 모듈을 참조하는 경우의 문제
11809정성태2/11/201912886.NET Framework: 807. ClrMD를 이용해 메모리 덤프 파일로부터 특정 인스턴스를 참조하고 있는 소유자 확인
11808정성태2/8/201913961디버깅 기술: 123. windbg - 닷넷 응용 프로그램의 메모리 누수 분석
11807정성태1/29/201912275Windows: 156. 가상 디스크의 용량을 복구 파티션으로 인해 늘리지 못하는 경우 [4]
11806정성태1/29/201912008디버깅 기술: 122. windbg - 덤프 파일로부터 PID와 환경 변수 등의 정보를 구하는 방법
11805정성태1/28/201913878.NET Framework: 806. C# - int []와 object []의 차이로 이해하는 제네릭의 필요성 [4]파일 다운로드1
11804정성태1/24/201911913Windows: 155. diskpart - remove letter 이후 재부팅 시 다시 드라이브 문자가 할당되는 경우
11803정성태1/10/201911401디버깅 기술: 121. windbg - 닷넷 Finalizer 스레드가 멈춰있는 현상
11802정성태1/7/201912783.NET Framework: 805. 두 개의 윈도우를 각각 실행하는 방법(Windows Forms, WPF)파일 다운로드1
11801정성태1/1/201913794개발 환경 구성: 427. Netsh의 네트워크 모니터링 기능 [3]
11800정성태12/28/201813085오류 유형: 509. WCF 호출 오류 메시지 - System.ServiceModel.CommunicationException: Internal Server Error
11799정성태12/19/201813916.NET Framework: 804. WPF(또는 WinForm)에서 UWP UI 구성 요소 사용하는 방법 [3]파일 다운로드1
11798정성태12/19/201813140개발 환경 구성: 426. vcpkg - "Building vcpkg.exe failed. Please ensure you have installed Visual Studio with the Desktop C++ workload and the Windows SDK for Desktop C++"
11797정성태12/19/201810514개발 환경 구성: 425. vcpkg - CMake Error: Problem with archive_write_header(): Can't create '' 빌드 오류
11796정성태12/19/201810167개발 환경 구성: 424. vcpkg - "File does not have expected hash" 오류를 무시하는 방법
11795정성태12/19/201812552Windows: 154. PowerShell - Zone 별로 DNS 레코드 유형 정보 조회 [1]
11794정성태12/16/20189943오류 유형: 508. Get-AzureWebsite : Request to a downlevel service failed.
11793정성태12/16/201811562개발 환경 구성: 423. NuGet 패키지 제작 - Native와 Managed DLL을 분리하는 방법 [1]
11792정성태12/11/201812330Graphics: 34. .NET으로 구현하는 OpenGL (11) - Per-Pixel Lighting파일 다운로드1
11791정성태12/11/201812321VS.NET IDE: 130. C/C++ 프로젝트의 시작 프로그램으로 .NET Core EXE를 지정하는 경우 닷넷 디버깅이 안 되는 문제 [1]
11790정성태12/11/201810656오류 유형: 507. Could not save daemon configuration to C:\ProgramData\Docker\config\daemon.json: Access to the path 'C:\ProgramData\Docker\config' is denied.
... 61  62  63  64  65  66  67  68  69  70  71  72  [73]  74  75  ...