您的位置:首页 > 其它

使用gettimeofday实现精确计时功能

2015-01-09 17:19 471 查看
gettimeofday的man说明:

GETTIMEOFDAY(2) Linux Programmer's Manual GETTIMEOFDAY(2)
NAME
gettimeofday, settimeofday - get / set time
SYNOPSIS
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv, const struct timezone *tz);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
settimeofday(): _BSD_SOURCE
DESCRIPTION
The functions gettimeofday() and settimeofday() can get and set the
time as well as a timezone. The tv argument is a struct timeval (as
specified in <sys/time.h>):
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
and gives the number of seconds and microseconds since the Epoch (see
time(2)). The tz argument is a struct timezone:
struct timezone {
int tz_minuteswest; /* minutes west of Greenwich */
int tz_dsttime; /* type of DST correction */
};
If either tv or tz is NULL, the corresponding structure is not set or
returned.
The use of the timezone structure is obsolete; the tz argument should
normally be specified as NULL. The tz_dsttime field has never been
used under Linux; it has not been and will not be supported by libc or
glibc. Each and every occurrence of this field in the kernel source

(other than the declaration) is a bug. Thus, the following is purely
of historic interest.
The field tz_dsttime contains a symbolic constant (values are given
below) that indicates in which part of the year Daylight Saving Time is
in force. (Note: its value is constant throughout the year: it does
not indicate that DST is in force, it just selects an algorithm.) The
daylight saving time algorithms defined are as follows :
DST_NONE /* not on dst */
DST_USA /* USA style dst */
DST_AUST /* Australian style dst */
DST_WET /* Western European dst */
DST_MET /* Middle European dst */
DST_EET /* Eastern European dst */
DST_CAN /* Canada */
DST_GB /* Great Britain and Eire */
DST_RUM /* Rumania */
DST_TUR /* Turkey */
DST_AUSTALT /* Australian style with shift in 1986 */
Of course it turned out that the period in which Daylight Saving Time
is in force cannot be given by a simple algorithm, one per country;
indeed, this period is determined by unpredictable political decisions.
So this method of representing timezones has been abandoned. Under
Linux, in a call to settimeofday() the tz_dsttime field should be zero.
Under Linux there are some peculiar "warp clock" semantics associated
with the settimeofday() system call if on the very first call (after
booting) that has a non-NULL tz argument, the tv argument is NULL and
the tz_minuteswest field is non-zero. In such a case it is assumed
that the CMOS clock is on local time, and that it has to be incremented
by this amount to get UTC system time. No doubt it is a bad idea to
use this feature.
Macros for operating on timeval structures are described in timer‐
add(3).
RETURN VALUE
gettimeofday() and settimeofday() return 0 for success, or -1 for fail‐

ure (in which case errno is set appropriately).
ERRORS
EFAULT One of tv or tz pointed outside the accessible address space.
EINVAL Timezone (or something else) is invalid.
EPERM The calling process has insufficient privilege to call settime‐
ofday(); under Linux the CAP_SYS_TIME capability is required.
CONFORMING TO
SVr4, 4.3BSD. POSIX.1-2001 describes gettimeofday() but not settimeof‐
day(). POSIX.1-2008 marks gettimeofday() as obsolete, recomending the
use of clock_gettime(2) instead.
NOTES
Traditionally, the fields of struct timeval were of type long.
SEE ALSO
date(1), adjtimex(2), time(2), ctime(3), ftime(3), capabilities(7),
time(7)
COLOPHON
This page is part of release 3.23 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at http://www.kernel.org/doc/man-pages/. Linux 2009-03-25 GETTIMEOFDAY(2)

以上都是凑字数的废话,中文说明如下:
使用C语言进行计时,在用户空间中可以使用C语言函数gettimeofday 得到时间,它的调用格式是:

[cpp]
view plaincopyprint?

#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv , const struct timezone *tz);
结构timeval的定义为:
strut timeval {long tv_sec; /* 秒数 */long tv_usec; /* 微秒数 */};

可以看出,使用这种方式计时,精度可达微秒,也就是10-6秒。进行计时的时候,我们需要前后调用两次gettimeofday,然后计算中间的差值:以下是写的一个小函数,客户端发送一个8K的数据给服务器,利用gettimeofday函数判断一次发送所需要的时间,也就是send()函数的一次调用时间。下面分别给出客户端和服务端的代码,客户端是可以链接TCP和UDP的客户端。中文注释有问题,我懒,不弄了,函数大家都能看得懂的。socket编程基础代码。

[cpp]
view plaincopyprint?

/*****************************************************
FileName: client.c
Description: Íø·¿Í»§¶Ë³ÌÐò£¬¿ÉÒÔÁ¬œÓtcpºÍudp·þÎñÆ÷
Author: wanxiao
*****************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/time.h>
#define MAXDATASIZE (1024*8)

/*ŽòÓ¡ÃüÁîÐвÎÊýÓ÷š*/
void useage()
{
printf("Command Error - ./filename [tcp] [ip_address] [port]/n");
printf(" ./filename [udp] [ip_address] [port]/n");
exit(1);
}

/*************************************************
Function: tcpclient
Description: tcp¿Í»§¶Ë£¬Á¬œÓ³É¹Šºó·¢ËÍÐÅÏ¢žøtcp·þÎñÆ÷
Input: ·þÎñÆ÷ipµØÖ·ip_address £¬·þÎñÆ÷¶Ë¿Úport (¶ŒÊÇcharÐÍ)
Output: ÎÞ
Return: ³É¹Š·µ»Ø0£»Ê§°Ü·µ»Ø-1
*************************************************/
int tcpclient(char *ip_address ,char *port)
{
printf("ipaddress :%s/n port :%s/n",ip_address,port);

struct sockaddr_in server; /*serverÌלÓ×ÖµØÖ·œá¹¹*/
int sockfd;
int ret;
int i_port = atoi(port); /*×Ö·ûŽ®×ª»»ÕûÐÍ*/
char msgbuf[MAXDATASIZE];
struct timeval start;
struct timeval end;
struct timezone tz;

/*socket*/
sockfd = socket(AF_INET, SOCK_STREAM , 0);
if(sockfd < 0)
{
perror("data stream socket create failed!/n");
return -1;
}

server.sin_family = AF_INET; /*ipv4*/
i_port = atoi(port);
server.sin_port = htons(i_port); /*°ó¶š¶Ë¿Ú*/

/*°ó¶šipµØÖ·*/
ret = inet_pton(AF_INET, ip_address, &server.sin_addr.s_addr);
if (ret <= 0)
{
printf("your ip address is unvalide!/n");
useage();
}

/*connect*/
ret = connect(sockfd,(struct sockaddr*) &server,sizeof(struct sockaddr_in));
if(ret < 0)
{
perror("data connection is failed!/n");
return -1;
}

printf("connect to server successfully!/n");
while(1)
{
memset(msgbuf, 0, sizeof(msgbuf));
/*send message to server*/
gettimeofday(&start, &tz);
ret = send(sockfd, msgbuf, sizeof(msgbuf), 0);
gettimeofday(&end, &tz);
if(ret == -1)
{
perror("send error");
return -1;
}
printf("The time between 'send' = %d u_secs/n",end.tv_usec-start.tv_usec);
//printf("send message sucessfully!/n");
}
}

/*************************************************
Function: udpclient
Description: udp¿Í»§¶Ë£¬Á¬œÓ³É¹Šºó·¢ËÍÐÅÏ¢žøudp·þÎñÆ÷
Input: ·þÎñÆ÷ipµØÖ·ip_address £¬·þÎñÆ÷¶Ë¿Úport (¶ŒÊÇcharÐÍ)
Output: ÎÞ
Return: ³É¹Š·µ»Ø0£»Ê§°Ü·µ»Ø-1
*************************************************/
int udpclient(char *ip_address ,char *port)
{
struct sockaddr_in server, client;
int clientfd;
int ret;
int server_port = atoi(port); /*×Ö·ûŽ®×ªÕûÐÍ*/
int client_port = 50000;
char msgbuf[]="This is a message from udp client/n";

server.sin_family = AF_INET;
server.sin_port = htons(server_port);
ret = inet_pton(AF_INET, ip_address, &server.sin_addr.s_addr);
if (ret <= 0)
{
printf("your ip address is unvalide!/n");
useage();
}

client.sin_family = AF_INET;
client.sin_port = htons(client_port);
client.sin_addr.s_addr = INADDR_ANY;

/*socket*/
clientfd = socket(AF_INET ,SOCK_DGRAM ,0);
if ( -1 == clientfd )
{
printf("create socket failed/n");
return -1;
}

/*bind*/
ret = bind(clientfd, (struct sockaddr *)&client, sizeof(client));
if ( -1 == ret)
{
printf("bind failed /n");
return -1;
}

printf("connect to server sucessfully!/n");

/*send message to server*/
ret = sendto(clientfd, msgbuf, sizeof(msgbuf), 0, (struct sockaddr*)&server, sizeof(server));
if(ret == -1)
{
perror("send to server");
return -1;
}

printf("send message sucessfully/n");

}

int main(int argc ,char **argv)
{
/*ÅжÏÃüÁîÐвÎÊý*/
if(argc != 4)
{
useage();
}

/*²ÎÊý1Ϊtcp£¬µ÷ÓÃtcpclient*/
if(strcmp(argv[1],"tcp") == 0)
{
tcpclient(argv[2] ,argv[3]);
}

/*²ÎÊý1Ϊudp£¬µ÷ÓÃudpclient*/
else if(strcmp(argv[1],"udp") == 0)
{
udpclient(argv[2] ,argv[3]);
}
else
{
useage();
exit(1);
}
return 0;
}

[cpp]
view plaincopyprint?

/*****************************************************
FileName: client.c
Description: tcp·þÎñ¶Ë£¬œÓÊÜ¿Í»§¶ËÇëÇ󲢎ðÓŠÊÕµœµÄ×Ö·ûŽ®
Author: wanxiao
Date: 2010-07-24
*****************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<netinet/in.h>
#define MAXCONN 10 /*listenº¯ÊýŒàÌý×îŽóÁ¬œÓÊý*/
#define MAXDATASIZE 1024*10 /*»º³åÇøŽóС*/
int main(int argc, char **argv)
{
if (argc != 2)
{
printf("Command Error -- filename [server port]/n");
return -1;
}

struct sockaddr_in server_sockaddr; /*Ö÷»úœá¹¹*/
struct sockaddr_in client_sockaddr; /*¿Í»§¶Ëœá¹¹*/
int addrlen = sizeof(struct sockaddr_in); /*µØÖ·œá¹¹×ÖœÚÊý*/
int recvbytes;
int sockfd;
int new_sockfd;
char buf[MAXDATASIZE];
/*socket*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
printf("socket success!, socket id = %d/n", sockfd);
server_sockaddr.sin_family = AF_INET;
server_sockaddr.sin_port = htons(atoi(argv[1]));
server_sockaddr.sin_addr.s_addr = INADDR_ANY; /*ÈÎÒâµØÖ·*/
/*bind*/
if(bind(sockfd, (struct sockaddr*)&server_sockaddr, sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
printf("bind success!/n");
/*listen*/
if(listen(sockfd, MAXCONN) == -1)
{
perror("listen");
exit(1);
}
printf("listening.../n");
/*accept*/
if((new_sockfd = accept(sockfd, (struct sockaddr*)&client_sockaddr, &addrlen)) == -1)
{
perror("accept");
exit(1);
}

while(1)
{
memset(buf, 0, sizeof(buf));
/*recvœÓÊÜ¿Í»§¶ËµÄÐÅÏ¢*/
if((recvbytes = recv(new_sockfd, buf, MAXDATASIZE, 0)) == -1)
{
perror("recv");
exit(1);
}
printf("received data size :%d/n", recvbytes);
}
close(sockfd);
return 0;
}

send文件可以打印出来每次时间,微妙级的精确计时工具,但是还有一个问题就是最后一次时间的输出实际上是第二个gettimeofday的调用后时间,这样实际上多加了一次gettimeofday的时间,应该是不够精准的,后续继续思考吧。希望看到的高人们给与指点…… ^_^!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: