Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/62.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何在linux中测量时间?_C_Linux_Timer - Fatal编程技术网

C 如何在linux中测量时间?

C 如何在linux中测量时间?,c,linux,timer,C,Linux,Timer,给定时间参数时,我想将数据写入文件: 例如,我得到x=7->意味着在接下来的7秒内将一些随机数据写入文件 我做那件事有点困难, 我尝试过使用:clock()和struct timeval,但没有成功 我尝试过的事情: struct timeval start, end; gettimeofday(&start, 0); while( gettimeofday(&end, 0) && end.tv_sec - start.tv_sec < sec ) {

给定时间参数时,我想将数据写入文件: 例如,我得到x=7->意味着在接下来的7秒内将一些随机数据写入文件 我做那件事有点困难, 我尝试过使用:clock()和struct timeval,但没有成功

我尝试过的事情:

struct timeval start, end;
gettimeofday(&start, 0);
while(  gettimeofday(&end, 0) && end.tv_sec - start.tv_sec < sec )
  {
    write....
  }
struct timeval开始、结束;
gettimeofday(&start,0);
while(gettimeofday(&end,0)和&end.tv_秒-start.tv_秒<秒)
{
写
}
但是它停止了时钟

我很想得到一些帮助。 谢谢

考虑一下操作顺序。。。尝试在
&

男:

因为gettimeofday()在循环中断时成功返回0

下面的代码已用
更正逻辑非运算符

while(  (!gettimeofday(&end, 0)) && end.tv_sec - start.tv_sec < sec )
  {
    write....
  }
while(!gettimeofday(&end,0))&end.tv_sec-start.tv_sec
如果成功,它将返回0,然后您的
条件将失败。尝试:

while(  (gettimeofday(&end, 0) == 0) && end.tv_sec - start.tv_sec < sec )
{
    write....
}
while((gettimeofday(&end,0)==0)和&end.tv_秒-start.tv_秒< /代码> 您应该考虑使用<代码> CcLogyGETTime<代码>,而不是<代码> GETTimeFoTe>代码>,该代码被称为<代码> POSIX 1-2008  < /P>。
#include <time.h>

int main()
{
    struct timespec start, end;
    int sec = 10; // Number of seconds

    clock_gettime(CLOCK_REALTIME, &start);
    while( !clock_gettime(CLOCK_REALTIME, &end)
           && end.tv_sec - start.tv_sec < sec )
    {
        // Write ...
    }
}

你什么意思?据我所知,操作顺序没有问题。问题是,我第一次使用(&end,0)时,时钟不再计数。我错了吗?虽然添加括号更清楚,但这不是问题所在-->@Grijesh Chauhan:你为什么这么做??为什么你要编辑一个错误的答案并改正它?这没有任何意义。@KarolyHorvath我的错误抱歉,请检查它是否正确。我的要求..提前谢谢!但是,它不停止时钟吗?不,你检查函数是否成功,如果它成功了,你检查值,如果你仍然是时间段,你进入while循环。考虑切换到函数…(
gettimeofday()
被POSIX标记为已过时)。@williampersell我查看了警报,但不知道如何使用它,如果我将其设置为警报(0),我如何计算已经过去了多少秒?你不计算。调用
报警
,然后输入“无限”循环写入数据。当计时器过期时,退出循环<代码>报警
很笨拙(1秒分辨率),但是有许多不同类型的计时器。谢谢!我对linux非常陌生,所以我不确定我是否理解使用clock_gettime和gettimeofday之间的区别。那么librt-lrt是做什么的呢?非常感谢。
#include <time.h>

int main()
{
    struct timespec start, end;
    int sec = 10; // Number of seconds

    clock_gettime(CLOCK_REALTIME, &start);
    while( !clock_gettime(CLOCK_REALTIME, &end)
           && end.tv_sec - start.tv_sec < sec )
    {
        // Write ...
    }
}
gcc myprogram.c -o myprogram -lrt