ctime、CTime、windows函数调用

在dll里是不能使用CTime类的,因为它里面有一个函数不被windows支持(找资料时看到这句话)。

如果要在控制台程序下使用MFC类,#include <afxwin.h>,另外,选择"Using MFC in a static library"。

  1. #include<time.h> 
  2. #include<iostream> 
  3. using namespace std; 
  4. int main() 
  5.     time_t timeval; 
  6.     timeval=time(NULL); 
  7.     cout<<"Time as local time is "<<ctime(&timeval)<<endl; 
  8.     return 0; 
  9. }

 

这个ctime输出还真是方便呢......比CTime类让我看着顺眼。要是能够比较快速地得到两个time的差值,作为我测试程序运行时间的工具,又能够方便地以一定的格式输出,那就perfect了!(比如说:deltaTime = time1-time2,得到差值,然后cout输出!如果有必要的话,何妨自己写一个类呢?)

  1. #include <iostream> 
  2. #include <time.h> 
  3. int main() 
  4. time_t curtime=time(0); 
  5. tm tim =*localtime(&curtime); 
  6. int day,mon,year; 
  7. day=tim.tm_mday; 
  8. mon=tim.tm_mon; 
  9. year=tim.tm_year; 
  10. std::cout<<year+1900<<"年"<<mon+1<<"月"<<day<<"日"<<std::endl; 
  11. system("pause"); 
  12. return 0 ; 
  13. 说明:struct tm 
  14. int tm_sec; /*秒,0-59*/ 
  15. int tm_min; /*分,0-59*/ 
  16. int tm_hour; /*时,0-23*/ 
  17. int tm_mday; /*天数,1-31*/ 
  18. int tm_mon; /*月数,0-11*/ 
  19. int tm_year; / *自1900的年数*/ 
  20. int tm_wday; /*自星期日的天数0-6*/ 
  21. int tm_yday; /*自1月1日起的天数,0-365*/ 
  22. int tm_isdst; /*是否采用夏时制,采用为正数* 
  23. 在VC++中,我们可以借助CTime时间类,获取系统当前日期: 
  24. CTime t = CTime::GetCurrentTime(); //获取系统日期 
  25. int d=t.GetDay(); //获得几号 
  26. int y=t.GetYear(); //获取年份 
  27. int m=t.GetMonth(); //获取当前月份 
  28. int h=t.GetHour(); //获取当前为几时 
  29. int mm=t.GetMinute(); //获取分钟 
  30. int s=t.GetSecond(); //获取秒 
  31. int w=t.GetDayOfWeek(); //获取星期几,注意1为星期天,7为星期六

仔细查找一下代码,发现下面CTime其实也不错。

  1. #include <afxwin.h>
  2. #include<iostream> 
  3. using namespace std; 
  4. int main() 
  5.     CTime t1 = CTime::GetCurrentTime();
  6.     
  7.     int j = 0;
  8.     for (int i=0;i<1000000000;i++)
  9.     {
  10.         j++;
  11.     }
  12.     CTime t2=CTime::GetCurrentTime();
  13.     CTimeSpan t = t2-t1;
  14.     cout<<t.GetMinutes()<<' '<<t.GetSeconds()<<endl;
  15.     return 0; 
  16. }

 

需要注意的:CTimeSpan虽然有<<操作符,但是是输出到CArchive文件的。

在以前,我写时间相关的代码,习惯是这样的:

  1. SYSTEMTIME time1,time2;
  2. GetSystemTime(&time1);
  3. //......
  4. GetSystemTime(&time2);
  5. cout<<time2.wSecond-time1.wSecond;

没有time2-time1这样的运算,不够精确,对吗?

 

你可能感兴趣的:(ctime、CTime、windows函数调用)