C语言 windows下如何获取开机时间

市面上好多电脑管家都
有的开机时间统计功能,具体的实现方法,windows下可以通过如下几个函数配合实现。

1》

C语言中的_strtime函数

函数名: _strtime
头文件: time.h
函数原型: char * _strtime(char *)
功能: 获取当前系统时间(不包括日期),函数以字符指针形式为返回.

函数应用举例1:
#include<time.h>
#include<string.h>
#include<stdio.h>
#include <conio.h>
void main()
{
char Now_time[30];
char *t;
t=Now_time;
strcpy(Now_time,_strtime(t));   
printf("%s",Now_time);
getch();
/*此形式一般用于理解*/
}
运行结果将打印出当前时间
函数应用举例2:


一般实用性的使用方法:
#include<time.h>
#include<stdio.h>
#include <conio.h>
void main()
{
char Now_time[30];
printf("%s",_strtime(Now_time));
getch();
}
运行结果将打印出当前时间
GetTickCount

GetTickCount,函数。GetTickCount返回(retrieve)从操作系统启动到现在所经过(elapsed)的毫秒数,它的返回值是DWORD。

函数功能:GetTickCount返回(retrieve)从 操作系统启动到现在所经过(elapsed)的毫秒数,它的返回值是DWORD。
函数原型:
DWORD GetTickCount(void);
CString s;
DWORD k=::GetTickCount(); //获取毫秒级数目
int se = k/1000; // se为秒
cout<<se<<endl;
库文件:kernl32.dll
C/C++头文件:winbase.h
windows程序设计中可以使用头文件 windows.h
//代替time函数来初始化随机数生成器
#include <iostream>
#include <windows.h>
#include <WinBase.h>
#include <ctime>
using namespace std;
int main()
{
int i, k, r;
for (i = 0; i < 10; i++)
{
srand (GetTickCount());
cout<<endl;
for (k = 0; k < 5; k++)
{
r = rand ();
cout<<r<<endl;
}
}
return 0;
}

3注意事项编辑

GetTickcount函数:它返回从 操作系统启动到当前所经过的毫秒数,常常用来判断某个方法执行的时间,其函数原型是DWORD GetTickCount(void),返回值以32位的双字类型DWORD存储,因此可以存储的最大值是2^32 ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0, MSDN中也明确的提到了:"Retrieves the number of milliseconds that have elapsed since the system was started, up to 49.7 days."。因此,如果是编写 服务器端程序,此处一定要万分注意,避免引起意外的状况。
特别注意:这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度为18ms。当需要有小于18ms的精度计算时,应使用StopWatch方法进行。

获取开机时间的具体案例如下:

获取结果如下图所示:


#include <time.h>
#include<windows.h>
#include <stdio.h>

void sleep( long wait );
void gettime();

int main( void )
{
	int flag=1;
	char time[128];
	_strtime(time);
	printf( "OS time:%s\n",time);
	//printf( "Delay for one seconds\n" );
	printf("开机时间:\n");
	do
	{
		gettime();
		sleep( 1000 );  //每间隔1000毫秒,也就是1秒刷新一次时间
	}while(flag);
	return 0;
}

void sleep( long wait )
{
	long goal;
	goal = wait + clock();
	while( goal > clock() );
}

void gettime()
{
	int i=GetTickCount();
	int h=(i/1000)/3600;
	int m=(i/1000)/60-h*60;
	int s=(i/1000)-h*3600-m*60;
	
	printf("%d小时%d分%d秒\n",h,m,s);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值