Time stamp in the C programming language

后端 未结 9 1434
别那么骄傲
别那么骄傲 2020-12-08 04:48

How do I stamp two times t1 and t2 and get the difference in milliseconds in C?

9条回答
  •  青春惊慌失措
    2020-12-08 05:23

    If you want to find elapsed time, this method will work as long as you don't reboot the computer between the start and end.

    In Windows, use GetTickCount(). Here's how:

    DWORD dwStart = GetTickCount();
    ...
    ... process you want to measure elapsed time for
    ...
    DWORD dwElapsed = GetTickCount() - dwStart;
    

    dwElapsed is now the number of elapsed milliseconds.

    In Linux, use clock() and CLOCKS_PER_SEC to do about the same thing.

    If you need timestamps that last through reboots or across PCs (which would need quite good syncronization indeed), then use the other methods (gettimeofday()).

    Also, in Windows at least you can get much better than standard time resolution. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:

    timeBeginPeriod(1);
    

    at the beginning of your program or process and a:

    timeEndPeriod(1);
    

    at the end, then the quantum will change to 1 ms, and you will get much better time resolution on the GetTickCount() call. However, this does make a subtle change to how your entire computer runs processes, so keep that in mind. However, Windows Media Player and many other things do this routinely anyway, so I don't worry too much about it.

    I'm sure there's probably some way to do the same in Linux (probably with much better control, or maybe with sub-millisecond quantums) but I haven't needed to do that yet in Linux.

提交回复
热议问题