getcurrent time on second或millisecond

时间:2013-12-01 04:06:01

标签: c

我正在做客户端服务器程序。我需要知道将文件名发送到服务器的时间,还需要知道接收文件的时间和两次之间的差异。

以下程序是什么意思?

以下程序有三个printf,但我能理解哪一个对我来说很合适?

int main(void)
{
  char buffer[30];
  struct timeval tv;

  time_t curtime,t;

  gettimeofday(&tv, NULL); 
  curtime=tv.tv_sec;
  t=mktime(localtime(&curtime));
  printf("%ld\n",t);
  printf("%ld\n",localtime(&curtime));
  strftime(buffer,30,"%m-%d-%Y  %T.",localtime(&curtime));
  printf("%s%ld\n",buffer,tv.tv_usec);
  return 0;
}

2 个答案:

答案 0 :(得分:0)

gettimeofday()返回一个timeval结构:

struct timeval { 
    time_t      tv_sec;     /* seconds since the Epoch*/
    suseconds_t tv_usec;    /* microseconds since the Epoch*/
};

您可以直接访问此信息,而无需使用上面[localtime()或mktime()]的任何格式化功能:

int main(void)
{
  struct timeval tv;

  gettimeofday(&tv, NULL);

  printf("seconds: %u :: microseconds: %u\n", (unsigned int)tv.tv_sec, (unsigned int)tv.tv_usec);
  return 0;
}

要计算经过的时间,我们需要两次得到时间,然后计算它们之间的差值:

#include <sys/time.h>
#include <stdio.h>
#include <unistd.h>

int main(void)
{
  struct timeval tv_start, tv_end;

  gettimeofday(&tv_start, NULL);

  /* do something */
  sleep(5);

  gettimeofday(&tv_end, NULL);

  printf("tv_start\n seconds: %u :: microseconds: %u\n\n", (unsigned int)tv_start.tv_sec, (unsigned int)tv_start.tv_usec);
  printf("tv_end\n seconds: %u :: microseconds: %u\n\n", (unsigned int)tv_end.tv_sec, (unsigned int)tv_end.tv_usec);

  /* convert both timeval structs to pure microseconds, and then subtract */
  int deltaInUSecs = (tv_end.tv_sec - tv_start.tv_sec)*1000000 - (tv_end.tv_usec - tv_start.tv_usec);
  printf("delta in microseconds\n %u\n\n", deltaInUSecs);

  return 0;
}

答案 1 :(得分:0)

以毫秒为单位获取当前时间:http://ideone.com/RBqisP

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>

int main(int argc, char *argv[]) 
{
    char cBuffer[100];
    time_t zaman;
    struct tm *ltime;
    static struct timeval _t;
    static struct timezone tz;

    time(&zaman);
    ltime = (struct tm *) localtime(&zaman);
    gettimeofday(&_t, &tz);

    strftime(cBuffer,40,"%d.%m.%y %H:%M:%S",ltime);
    sprintf(cBuffer, "%s.%d", cBuffer,(int)_t.tv_usec);

    printf(" %s \n",cBuffer);

    return 0;
}

持续时间:http://ideone.com/NvXEQv

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>

int main (int argc, char *argv[])
{
    double cBuffer1;
    double cBuffer2;
    time_t zaman;
    struct tm *ltime;
    static struct timeval _t;
    static struct timezone tz;

    time(&zaman);
    ltime = (struct tm *) localtime(&zaman);

    gettimeofday(&_t, &tz);
    cBuffer1 = (double)_t.tv_sec + (double)_t.tv_usec/(1000*1000);
    printf(" %f \n",cBuffer1);

    sleep(1);

    gettimeofday(&_t, &tz);
    cBuffer2 = (double)_t.tv_sec + (double)_t.tv_usec/(1000*1000);  
    printf(" %f \n", cBuffer2);

    printf(" duration : %f \n", cBuffer2-cBuffer1);

    return 0;
}