网站首页 > 基础教程 正文
time()和clock()是C语言中的两种计时函数,在测量某段程序的运行时间时经常会用到,那么这两种计时有什么区别呢?
time函数:time_t time(time_t* timer),其功能是返回从自纪元 Epoch(UTC:1970-01-01 00:00:00)到当前时刻的秒数。
time_t time (time_t* timer);
Get the current calendar time as a value of type time_t.
The function returns this value, and if the argument is not a null pointer, it also sets this value to the object pointed by timer.
clock函数:clock_t clock(void),其功能是返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数。
clock_t clock (void);
Returns the processor time consumed by the program.
The value returned is expressed in clock ticks, which are units of time of a constant but system-specific length (with a relation of CLOCKS_PER_SEC clock ticks per second).
下面用一段程序来说明time和clock的计时结果。
上面的程序运行结果如下:
可以看到,用time函数的计时是人们正常意识上的秒数,而clock函数的计时所表示的是占用CPU的时钟单元,而sleep(2)并不占用cpu资源。
sleep函数:unsigned sleep(unsigned seconds),其功能是把进程挂起一段时间。
difftime函数:double difftime(time_t time1, time_t time2),其功能是返回 time1 和 time2 之间相差的秒数 (time1 - time2)。
clock_t是一个长整形数。在time.h头函数中定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,用于将clock()函数的结果转化为以秒为单位的量,但是这个量的具体值是与操作系统相关的。
- 在Windows系统中,CLOCKS_PER_SEC 为 1000
- 在Mac/Linux系统中,CLOCKS_PER_SEC 为 1000000
猜你喜欢
- 2024-10-19 Python3 datetime模块指南:日期时间操作、时区管理与实战案例
- 2024-10-19 C++及数据结构复习笔记,类和对象很简单?为啥好多程序员还不会
- 2024-10-19 Linux时间和日期 linux 时间 表示方法
- 2024-10-19 C/C++的8种时间度量方式以及代码片段
- 2024-10-19 Python实战:使用 datetime模块处理时间日期的全方位指南
- 2024-10-19 C++编程的 42 条建议(四) c++编程100例
- 2024-10-19 mount with noatime - 合理关闭atime提高服务器性能
- 2024-10-19 linux下连续三次fork()——深度理解进程创建函数
- 2024-10-19 C函数time和clock的计时区别 c计时器函数
- 2024-10-19 win进程弹出Microsoft Visual C++ Runtime Library的解决办法
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)