#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main()
{
unsigned char time1[] = { 10, 8, 31, 9, 26 }
unsigned char time2[] = { 10, 8, 31, 9, 50 }
struct tm t1 = {0}
struct tm t2 = {0}
time_t _t1
time_t _t2
double diff
t1.tm_year = time1[0] + 100
t1.tm_mon = time1[1]
t1.tm_mday = time1[2]
t1.tm_hour = time1[3]
t1.tm_min = time1[4]
t2.tm_year = time2[0] + 100
t2.tm_mon = time2[1]
t2.tm_mday = time2[2]
t2.tm_hour = time2[3]
t2.tm_min = time2[4]
_t1 = _mkgmtime( &t1 )
_t2 = _mkgmtime( &t2 )
diff = difftime(_t2, _t1 )
printf( "相差 %.0f 分钟n", diff / 60 )
}
扩展资料
C语言中有两个相关的函数用来计算时间差,分别是:
time_t time( time_t *t) 与 clock_t clock(void)
头文件: time.h
计算的时间单位分别为: s , ms
time_t 和 clock_t 是函数库time.h 中定义的用来保存时间的数据结构
返回值:
1、time : 返回从公元1970年1月1号的UTC时间从0时0分0秒算起到现在所经过的秒数。如果参数 t 非空指针的话,返回的时间会保存在 t 所指向的内存。
2、clock:返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数。 1单元 = 1 ms。
所以我们可以根据具体情况需求,判断采用哪一个函数。
具体用法如下例子:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
time_t c_start, t_start, c_end, t_end
c_start = clock() //!<单位为ms
t_start = time(NULL) //!<单位为s
system("pause")
c_end = clock()
t_end = time(NULL)
//!<difftime(time_t, time_t)返回两个time_t变量间的时间间隔,即时间差
printf("The pause used %f ms by clock()n",difftime(c_end,c_start))
printf("The pause used %f s by time()n",difftime(t_end,t_start))
system("pause")
return 0
}
因此,要计算某一函数块的占用时间时,只需要在执行该函数块之前和执行完该函数块之后调用同一个时间计算函数。再调用函数difftime()计算两者的差,即可得到耗费时间。
标准库的time.h里有时间函数
time_t time (time_t *timer)
计算从1970年1月1日到当前系统时间,并把结果返回给timer变量,
函数本身返回的也是这个结果.time_t这个类型其实就是一个int.
另有:
double difftime ( time_t timer2, time_t timer1 )
把返回time2和time1所储存的时间的差.
希望能够我的思路可以帮助你:
①如果password="124567"时,欢迎进入!
②如果password != "124567"时,等待15分钟!
③等待15分钟后返回重新输入密码!
#include <stdio.h>
#include <string.h>
#include<windows.h>
int main()
{
char str[20], password
int x,i
//执行4次循环0,1,2,3
for(x=0x<=3 &&strcmp(str,"1234567")!=0x++)
{
printf("Enter password please:")
scanf("%s",&str)
//当密码错误时提示输入错误!
if(strcmp(str,"1234567")!=0)
{
printf("Input error!n")
}
//当错误了3次时执行等待,并重置x的初值
if(x==2)
{
printf("Please wait another 15 min.")
for(i=0i<=(15*60)i++)
Sleep(1000)//停滞一秒
//重置x的初值
x=0
}
else
//密码输入正确时跳出循环,执行for循环之外的语句
{
if(strcmp(str,"1234567")==0)
printf("Welcomen")
break
}
}
//可以插入验证后要执行的代码
return 0
}
C语言中的头文件time.h中定义了库函数clock(),它返回的是从程序运行开始算起的时间,一时钟周期为单位,time.h还定义了符号:CLOCKS_PER_SEC,即一秒钟的时钟周期。这样就简单了,在头文件中加入#include<time.h>,在程序main()主函数的开头定义long now=0;并给把clock()赋值给now,即now=clock();记录程序开始时的时间,clock()会继续增加,但now已经确定为开始那一时刻clock()的值,在程序结尾,算式clock()-now就是程序执行所需的时间,但是是以时钟周期为单位的,如果想得到以秒为单位的时间只要输出(clock()-now)/CLOCKS_PER_SEC就是了,即在程序结尾添加
printf("%lf",(clock()-now)/CLOCKS_PER_SEC);就可以了。
以上就是关于c语言编程,怎么计算时间全部的内容,如果了解更多相关内容,可以关注醉学网,你们的支持是我们更新的动力!