C语言时间处理实例分享

2020-01-06 13:23:45王振洲

易采站长站为您分析C语言时间处理实例分享的相关资料,需要的朋友可以参考下

一、简介

时间处理在编程中经常遇到,包括程序的运行时间和显示时间等。在标准C中, 日期和时间的处理包含在 time.h 的头文件中,需要使用日期和时间相关的类型的函数的话, 需要导入time.h.

二、实例

1、计算时差

 

 
  1. #include <stdio.h>   #include <sys/time.h>  
  2. #include <unistd.h>    
  3. int main()  { 
  4. struct timeval start, end;  unsigned long spend_time; 
  5.   gettimeofday( &start, NULL ); 
  6. printf("start : %d.%dn", start.tv_sec, start.tv_usec);  sleep(1); 
  7. gettimeofday( &end, NULL );  printf("end : %d.%dn", end.tv_sec, end.tv_usec); 
  8.   //微秒时差 
  9. spend_time=1000000*(end.tv_sec-start.tv_sec)+(end.tv_usec-start.tv_usec);  printf("%ldn",spend_time); 
  10.   return 0; 

编译

gcc -g -o time_diff time_diff.c

运行

C语言时间处理实例分享

以上所述就是本文的全部内容了,希望大家能够喜欢。