How to obtain system time in C Language

Source: Internet
Author: User

How to obtain system time in C Language

C LanguageHow to get the time? How accurate?
1 use time_t time (time_t * timer) to be accurate to seconds
2 using clock_t clock (), the CPU time is accurate to 1/CLOCKS_PER_SEC.
3. Calculate the time difference using double difftime (time_t timer1, time_t timer0)
4 Use DWORD GetTickCount () precise to milliseconds
5. If you use the CTime class of MFC, you can use CTime: GetCurrentTime () to precise to seconds.
6. You can use
BOOL QueryPerformanceFrequency (LARGE_INTEGER * lpFrequency)
Obtain the counter frequency of the system.
BOOL QueryPerformanceCounter (LARGE_INTEGER * lpPerformanceCount)
Obtains the counter value.
Then, divide the difference between two counters by Frequency to get the time.
7. Multimedia Timer Functions
The following functions are used with multimedia timers.
TimeBeginPeriod/timeEndPeriod/timeGetDevCaps/timeGetSystemTime
//************************************** *******************************
// Use standard C to obtain the current system time

I. time () function

The time (& rawtime) function returns the number of seconds from January 1, January 1, 1970, in seconds, and is stored in rawtime.
# Include "time. h"
Void main ()
{
Time_t rawtime;
Struct tm * timeinfo;
Time (& rawtime );
Timeinfo = localtime (& rawtime );
Printf ("/007The current date/time is: % s", asctime (timeinfo ));
Exit (0 );
}
========================
# Include -- the required time function header file
Time_t -- time type (time. h is defined as typedef long time_t; tracing, time_t is long)
Struct tm -- time structure, which is defined as follows:
Int tm_sec;
Int tm_min;
Int tm_hour;
Int tm_mday;
Int tm_mon;
Int tm_year;
Int tm_wday;
Int tm_yday;
Int tm_isdst;
Time (& rawtime); -- get time, in seconds, from January 1, January 1, 1970, stored in rawtime
Localtime (& rawtime); -- convert to local time, tm Time Structure
Asctime () -- convert to standard ASCII time format:
Week Month day hour: minute: second year

-----------------------------------------------------------------------------
Ii. clock () function. Use the clock () function to obtain the millisecond-level time after the system is started. divide it by CLOCKS_PER_SEC and replace it with the standard c function.
Clock_t clock (void );
# Include
Clock_t t = clock ();
Long sec = t/CLOCKS_PER_SEC;
It records the clock cycle, and the implementation does not seem very accurate and requires experimental verification;
---------------------------------------------------------------------------
3. gettime (& t); it is said that the time structure of tc2.0 contains millisecond Information
# Include
# Include
Int main (void)
{
Struct time t;
Gettime (& t );
Printf ("The current time is: % 2d: % 02d: % 02d. % 02d/n ",
T. ti_hour, t. ti_min, t. ti_sec, t. ti_hund );
Return 0;
}
Time is a struct, in which the member function ti_hund is millisecond...

--------------------------------------------------------------------------------
4. GetTickCount (), which is a function commonly used in windows to calculate the running time;
DWORD dwStart = GetTickCount ();
// Run your program code here
DWORD dwEnd = GetTickCount ();
Then (dwEnd-dwStart) Is your program running time, in milliseconds
This function is only accurate to 55 ms, and one tick is 55 ms.
--------------------------------------------------------------------------------
5. timeGetTime () t, imeGetTime () is basically equal to GetTickCount (), but the accuracy is higher
DWORD dwStart = timeGetTime ();
// Run your program code here
DWORD dwEnd = timeGetTime ();
Then (dwEnd-dwStart) Is your program running time, in milliseconds
Although the unit of returned values should be ms, the legend shows that the precision is only 10 ms.
========================================================== =
//************************************** * *************************** Unix
# Unix time-related, also standard library
//************************************** *******************************
1. The timegm function only converts the struct tm structure to the time_t structure without the time zone information;
Time_t timegm (struct tm * tm );
2. mktime uses time zone information
Time_t mktime (struct tm * tm );
The timelocal function is a GNU extension equivalent to the posix function mktime.
Time_t timelocal (struct tm * tm );
3. The gmtime function only converts the time_t structure to the struct tm structure without the time zone information;
Struct tm * gmtime (const time_t * clock );
4. Use the time zone information for localtime
Struct tm * localtime (const time_t * clock );
1. Obtain the time and set the time in stime.
Time_t t;
T = time (& t );
2. The stime parameter should be the GMT time, which is set to the local time according to the local time zone;
Int stime (time_t * tp)
3. UTC = true indicates that the Daylight Saving Time is used;
4. The modification time and other information of the file are all stored in GMT. Different systems use localtime to convert the local time after obtaining the modification time;
5. We recommend that you use setup to set the time zone;
6. You can change the time zone to the setting in/etc/sysconfig/clock and then re-apply ln-fs/usr/share/zoneinfo/xxxx/xxx/etc/localtime.
Time_t can only represent the range of 68 years, that is, mktime can only return time_t in the range of 1970-2038
Check whether your system has time_t64, which can indicate a larger time range.
//************************************** * ************************* Windows
# Some differences in Window
//************************************** *******************************

I. CTime () Class
VC Programming generally uses the CTime class to obtain the current date and time

CTime t = GetCurrentTime ();
The SYSTEMTIME structure contains millisecond information.
Typedef struct _ SYSTEMTIME {
WORD wYear;
WORD wMonth;
WORD wDayOfWeek;
WORD wDay;
WORD wHour;
WORD wMinute;
WORD wSecond;
WORD wMilliseconds;
} SYSTEMTIME, * PSYSTEMTIME;
SYSTEMTIME t1;
GetSystemTime (& t1)
CTime curTime (t1 );
Word ms = t1.wMilliseconds;
SYSTEMTIME interval m;
: GetLocalTime (& M );
_ Strtime () in time. h // can only be used in windows
Char t [11];
_ Strtime (t );
Puts (t );

//*****************************
Obtain the current date and time
CTime tm = CTime: GetCurrentTime ();
CString str = tm. Format ("% Y-% m-% d ");
In VC, we can use the CTime class to obtain the current date of the system. The usage is as follows:
CTime t = CTime: GetCurrentTime (); // obtain the system date, stored in t
Int d = t. GetDay (); // obtain the current date
Int y = t. GetYear (); // get the current year
Int m = t. GetMonth (); // get the current month
Int h = t. GetHour (); // obtain the current time
Int mm = t. GetMinute (); // get the current minute
Int s = t. GetSecond (); // get the current second
Int w = t. GetDayOfWeek (); // obtain the day of the week. Note that 1 is Sunday and 7 is Saturday.

Ii. CTimeSpan class
To calculate the difference between the two periods, you can use the CTimeSpan class. The usage is as follows:
CTime t1 (1999, 3, 19, 22, 15, 0 );
CTime t = CTime: GetCurrentTime ();
CTimeSpan span = t-t1; // calculate the interval between the current system time and time t1
Int iDay = span. GetDays (); // obtain the total number of days of the interval.
Int iHour = span. GetTotalHours (); // obtain the total number of hours
Int iMin = span. GetTotalMinutes (); // obtain the total number of minutes
Int iSec = span. GetTotalSeconds (); // gets the total number of seconds

------------------------------------------------------------------------------

3. _ timeb () function
_ Timeb is defined in SYS/TIMEB. H and has four fields.
Dstflag
Millitm
Time
Timezone
Void _ ftime (struct _ timeb * timeptr );
Struct _ timeb timebuffer;
_ Ftime (& timebuffer );
Take the current time: the document can be described in ms. Someone tests it, as if it could only be 16 ms!

4. Set a timer
Define TIMER ID
# Define TIMERID_JISUANFANGSHI 2
Set the clock in a proper place, where you need to start its function;
SetTimer (TIMERID_JISUANFANGSHI, 200, NULL );
Destroy the clock when no timer is required
KillTimer (TIMERID_JISUANFANGSHI );
Message ing corresponding to VC program
Void CJisuan: OnTimer (UINT nIDEvent)
{Switch (nIDEvent )}
Bytes ---------------------------------------------------------------------------------------
# How to set the current system time ------------------------------------- windows
SYSTEMTIME m_myLocalTime, * lpSystemTime;
M_myLocalTime.wYear = 2003;
M_myLocalTime.wM;
M_myLocalTime.wDay = 1;
M_myLocalTime.wHour = 0;
M_myLocalTime.wMinute = 0;
M_myLocalTime.wSec;
M_myLocalTime.wMillisec;
LpSystemTime = & m_myLocalTime;
If (SetLocalTime (lpSystemTime) // you cannot change it to SetSystemTime ().
MessageBox ("OK! ");
Else
MessageBox ("Error! ");
SYSTEMTIME m_myLocalTime, * lpSystemTime;
M_myLocalTime.wYear = 2003;
M_myLocalTime.wM;
M_myLocalTime.wDay = 1;
LpSystemTime = & m_myLocalTime;
If (SetDate (lpSystemTime) // it cannot be changed to SetSystemTime ().
MessageBox ("OK! ");
Else
MessageBox ("Error! ");

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.