首页 > 编程知识 正文

c语言time函数定义,c中time的函数怎么用

时间:2023-05-03 05:21:15 阅读:228753 作者:1519

c语言time函数怎么使用

In this article, we’ll take a look at using the time() function in C/C++.

在本文中,我们将研究在C / C ++中使用time()函数。

The time() function is a useful utility function that we can use to measure the elapsed time of our program.

time()函数是一个有用的实用程序函数,可用于测量程序的经过时间。

Let’s look at how we can use this function, using some simple examples!

让我们来看一些简单的例子,看看如何使用此功能!



C / C ++中time()函数的基本语法 (Basic Syntax of the time() function in C/C++)

This function belongs to the header file <time.h>, so we must include this before calling time().

该函数属于头文件<time.h> ,因此在调用time()之前必须包含此文件。

#include <time.h>time_t time(time_t *tloc);

This takes in a pointer to a time_t datatype and returns the time elapsed since 00:00:00 UTC, January 1, 1970.

这将获取一个指向time_t数据类型的指针,并返回从1970年1月1日UTC 00:00:00开始经过的时间。

The time value returned is in seconds, so you must make suitable conversions from it.

返回的时间值以秒为单位,因此您必须从中进行适当的转换。

If tloc is not a null pointer, the returned value is also stored in the object pointed to by second.

如果tloc 不是空指针,则返回的值也存储在second指向的对象中。

Otherwise, if tloc is NULL, the return value is not stored anywhere.

否则,如果tloc为NULL ,则返回值不会存储在任何地方。

Let’s look at some simple examples now.

现在让我们看一些简单的例子。

在C / C ++中使用time()–一些示例 (Using time() in C/C++ – Some Examples)

Let’s first look at the case when tloc is a NULL pointer.

首先让我们看一下tloc是NULL指针的情况。

#include <stdio.h>#include <time.h>int main() { time_t num_seconds = time(NULL); // Passing NULL to time() printf("Since 1st January 1970 UTC, No. of seconds = %d, No. of days = %d", (int)num_seconds, (int)num_seconds/86400); return 0;}

Output

输出量

Since 1st January 1970 UTC, No. of seconds = 1592317455, No. of days = 18429

As of the time of writing (June 16 2020), this is indeed true!

截至撰写本文时(2020年6月16日),确实如此!

Now, let’s go to the second case, when tloc is not NULL.

现在,让我们转到第二种情况,即tloc不为NULL时。

In this case, since the return value will be stored to the pointer location, there is no need to assign it separately!

在这种情况下,由于返回值将存储在指针位置,因此无需单独分配它!

#include <stdio.h>#include <time.h>int main() { time_t tloc; time(&tloc); // Storing the return value to tloc printf("Since 1st January 1970 UTC, No. of seconds = %d, No. of days = %d", (int)tloc, (int)tloc/86400); return 0;}

This will give a similar output as before.

这将提供与以前相似的输出。



结论 (Conclusion)

In this article, we learned about using the time() function in C / C++, to get the time elapsed since the first epoch.

在本文中,我们学习了如何在C / C ++中使用time()函数来获取自第一个时期以来所经过的时间。

For more content on C and C++, do go through our tutorial section on C programming!

有关C和C ++的更多内容,请阅读我们有关C编程的教程部分 !

参考资料 (References) Linux Manual Page on time() in C

Linux手册页 on time()in C



翻译自: https://www.journaldev.com/41447/time-function-in-c-plus-plus

c语言time函数怎么使用

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。