C函数time和clock的计时区别
clock_t clock ;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 .下面用一段程序来说明time和clock
clock_t clock ;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 .下面用一段程序来说明time和clock的计时结果。上面的程序运行结果如下:可以看到,用time函数的计时是人们正常意识上的秒数,而clock函数的计时所表示的是占用CPU的时钟单元,而sleep并不占用cpu资源。difftime函数:double difftime,其功能是返回 time1 和 time2 之间相差的秒数 。在time.h头函数中定义了一个常量CLOCKS_PER_SEC,它用来表示一秒钟会有多少个时钟计时单元,用于将clock()函数的结果转化为以秒为单位的量,但是这个量的具体值是与操作系统相关的。在Windows系统中,CLOCKS_PER_SEC 为 1000在Mac/Linux系统中,CLOCKS_PER_SEC 为 1000000
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()函数的结果转化为以秒为单位的量,但是这个量的具体值是与操作系统相关的。