C语言 如何使用 gettimeofday() 获取我的程序的运行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2125219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:14:14  来源:igfitidea点击:

How to get the running of time of my program with gettimeofday()

ctimetype-conversion

提问by Ritwik Bose

So I get the time at the beginning of the code, run it, and then get the time.

所以我在代码的开头获取时间,运行它,然后获取时间。

struct timeval begin, end;
gettimeofday(&begin, NULL);

//code to time

gettimeofday(&end, NULL);
//get the total number of ms that the code took:
unsigned int t = end.tv_usec - begin.tv_usec;

Now I want to print it out in the form "**code took 0.007 seconds to run" or something similar.

现在我想以“**代码运行时间为 0.007 秒”或类似的形式打印出来。

So two problems:

所以有两个问题:

1) t seems to contain a value of the order 6000, and I KNOW the code didn't take 6 seconds to run.

1) t 似乎包含订单 6000 的值,我知道代码运行时间不超过 6 秒。

2) How can I convert t to a double, given that it's an unsigned int? Or is there an easier way to print the output the way I wanted to?

2) 我怎样才能将 t 转换为双精度型,因为它是一个无符号整数?或者有没有更简单的方法可以按照我想要的方式打印输出?

回答by SoapBox

timevalcontains two fields, the seconds part and the microseconds part.

timeval包含两个字段,秒部分和微秒部分。

tv_usec(umeaning the greek letter mu, which stands for micro) is the microseconds. Thus when you get 6000, that's 6000 microseconds elapsed. tv_seccontains the seconds part.

tv_usecu表示希腊字母mu,代表微)是微秒。因此,当您获得 6000 时,即过去了 6000 微秒。 tv_sec包含秒部分。

To get the value you want as a double use this code:

要获得您想要的双重价值,请使用以下代码:

double elapsed = (end.tv_sec - begin.tv_sec) + 
              ((end.tv_usec - begin.tv_usec)/1000000.0);

Make sure you include the tv_secpart in your calculations. gettimeofdayreturns the current time, so when the seconds increments the microsecond will go back to 0, if this happens while your code is running and you don't use tv_secin your calculation, you will get a negative number.

确保将tv_sec零件包括在计算中。 gettimeofday返回当前时间,因此当秒增加时,微秒将返回到 0,如果在您的代码运行时发生这种情况并且您没有tv_sec在计算中使用,您将得到一个负数。

回答by Michael Dickens

1) That's because usecis not 6000 milliseconds, it's 6000 microseconds (6 milliseconds or 6 one-thousandths of a second).

1) 那是因为usec不是 6000 毫秒,而是 6000 微秒(6 毫秒或 6 千分之一秒)。

2) Try this: (double)t / 1000000That will convert t to a double, and then divide it by one million to find the number of seconds instead of the number of microseconds.

2) 试试这个:(double)t / 1000000这会将 t 转换为双精度值,然后将其除以一百万以找到秒数而不是微秒数。