我正在尝试以秒精度打印ISO-8601中的时间.YYYY-MM-DDTHH:MM:SS.S
这是我的代码:
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void milli_time(char* dest, struct timeval* t)
{
struct tm* timeInfo;
strftime(dest, 22, "%Y-%m-%dT%t", localtime(&t->tv_sec));
printf("%s\n", dest);
fflush(stdout);
char deciTime[3];
sprintf(deciTime, ".%lu", ((t->tv_usec)/100000ul));
strcat(dest, deciTime);
}
int main()
{
struct timeval* theTime;
char timeString[32];
gettimeofday(theTime, NULL);
printf("%lu.%lu\n", theTime->tv_sec, theTime->tv_usec);
milli_time(timeString, theTime);
printf("%s\n", timeString);
fflush(stdout);
}
Run Code Online (Sandbox Code Playgroud)
每次运行它的输出是:
134520616.3077826840
1974-04-06T17:50:16
1974-04-06T17:50:16.30778
Run Code Online (Sandbox Code Playgroud)
我注意到的另一件事是tv_usec超过一百万.
我收到了一些奇怪的编译错误.这是一个家庭作业(帮助还可以).我们的想法是实现一个程序来测试用户每秒可以进入"输入"的程度.我应该使用gettimeofday为每个"输入"获取一些时间值,然后找出平均时间和标准偏差...我试图通过检查标准输入'\n'来做到这一点,然后如果是的,使用gettimeofday填充timeval结构,然后将所述结构存储在一个数组中供以后使用...
我在编译(gcc -Wextra homework1.c)时得到的错误是:
homework1.c: In function ‘main’:
homework1.c:19:29: error: expected ‘]’ before ‘;’ token
homework1.c:27:17: error: expected ‘)’ before ‘;’ token
homework1.c:32:4: error: ‘entry_array’ undeclared (first use in this function)
homework1.c:32:4: note: each undeclared identifier is reported only once for each function it appears in
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我得到前两个语法错误然后我无法理解为什么当我在"main"的开头明确地声明它时,"entry_array"是未声明的.建议?
我觉得我因为不知道如何使用timeval结构而被烧毁......最初我试图像对待任何其他结构一样全局定义struct timeval但是在覆盖struct timeval的定义时遇到错误.这是因为它是在"sys/time.h"库中定义的吗?
这是代码:
GNU nano 2.2.6 File: homework1.c
//prototypes
int GetAverage(long array[]);
int GetStdDev(long array[]);
//# of keystrokes tracked by user
#define MAX_STROKES 1;
int main(int argv, char ** argc) …Run Code Online (Sandbox Code Playgroud) 使用gettimeofday()的简单C程序在没有任何标志(gcc-4.5.1)的情况下编译时工作正常但在使用标志-mno-sse编译时不提供输出.
#include <stdio.h>
#include <stdlib.h>
int main()
{
struct timeval s,e;
float time;
int i;
gettimeofday(&s, NULL);
for( i=0; i< 10000; i++);
gettimeofday(&e, NULL);
time = e.tv_sec - s.tv_sec + e.tv_usec - s.tv_usec;
printf("%f\n", time);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我有CFLAGS = -march = native -mtune = native有人可以解释为什么会这样吗?程序正常返回正确的值,但在启用-mno-sse编译时打印"0".
我需要计算运行某个函数所需的时间并运行以下代码,以纳秒为单位记录并输出一段代码的执行时间
并且也有任何区别
struct timeval timer_spent & timeval timer_spent
/* Put this line at the top of the file: */
#include <sys/time.h>
/* Put this right before the code you want to time: */
struct timeval timer_start, timer_end;
gettimeofday(&timer_start, NULL);
/* Put this right after the code you want to time: */
gettimeofday(&timer_end, NULL);
double timer_spent = timer_end.tv_sec - timer_start.tv_sec + (timer_end.tv_usec - timer_start.tv_usec);
printf("Time spent: %.6f\n", timer_spent)/1000000.0;
Run Code Online (Sandbox Code Playgroud)
但我需要精确的时间,以纳秒为单位.我对timeval结构没有完全的了解.
亲切地帮助我们.. !!