如何精確計算時間到微秒級

來源:互聯網
上載者:User

 一、

windows系統中取得微妙和毫秒級的時間2008-04-23 11:57

windows系統中得到精確到微妙的時間(通過cpu頻率計算)
#include <windows.h>
#include <iostream>
(取得cpu頻率)
LARGE_INTEGER t1,t2,feq;
QueryPerformanceFrequency(&feq);//每秒跳動次數
QueryPerformanceCounter(&t1);//測前跳動次數
for(int i = 0;i<10000;i++);
QueryPerformanceCounter(&t2);//測後跳動次數
double d=((double)t2.QuadPart-(double)t1.QuadPart)/((double)feq.QuadPart);//時間差秒
std::cout<<d<<std::endl;

windows系統中得到精確到毫妙的時間

DWORD GetTickCount(VOID) ;
SDk: The GetTickCount function retrieves the number of milliseconds that have elapsed since Windows was started.

CTime t = CTime::GetCurrentTime();
SDK:This method obtains a CTime object that represents the current time.

 

二、

我最初用的函數是timeGetTime(),該函數只能精確到ms,具體用法如下

         #include <mmsystem.h>

         DOWD begin, end;

         begin = timeGetTime();

        //你要計算的程式片斷

         end = timeGetTime();

          CString strTime;
         strTime.Format("%d",end - start);

           最後在你的工程裡面設定linker-input-Additional Dependencies 加上Winmm.lib

           如果要顯示微妙級的就不夠用了,可以採用系統的計數器來實現。

           LARGE_INTEGER frequency ;
           QueryPerformanceFrequency(&frequency );
   
            LARGE_INTEGER start, end;
            QueryPerformanceCounter(&start);
            //你要計算的程式片斷  
 
           QueryPerformanceCounter(&end);

           int time=( ((end.QuadPart - start.QuadPart) * 1000000)/frequency.QuadPart);

           有用的連結:http://dev.csdn.net/develop/article/41/41104.shtm

                                   http://dev.csdn.net/article/74/74169.shtm

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.