C/C++中系统时间的实现

来源:互联网 发布:linux 内核调试kgd 编辑:程序博客网 时间:2024/06/08 07:33

怎么在程序中,实现让程序计时呢?也就是说怎么让程序等待我想要的秒数?可以使用C/C++提供的系统函数clock()实现:

ANSI C和C++中的库函数中有一个叫做clock()的函数,专门用来实现计时的。但是clock()不能返回会秒数,因为秒数跟十进制一样是人类的计时方法,计算机中是使用计算机硬件的系统时钟单位来计时的。该函数返回的值可能是一个long型的,也有可能是unsigned long型的,那么怎么才能实现可移植性呢?其实,在time.h(C++:ctime)中定义了一个符号常量——CLOCKS_PER_SEC,该常量等于每秒包含的系统时间单位数。因此可以如下实现:

C语言代码:

#include <stdio.h>#include <time.h>int main (void){float sec;clock_t delay;clock_t start;printf ("Please enter the delay seconds!\n");scanf ("%f",&sec);delay = sec * CLOCKS_PER_SEC;printf ("Starting\a\n");start = clock();while (clock() - start < delay);return 0;}
C++代码:

#include <iostream>#include <ctime>int main (void){using namespace std;float sec;clock_t delay;clock_t start;cout << "Please enter the delay seconds:" << endl;cin >> sec;delay = sec * CLOCKS_PER_SEC;cout << "Starting\a\n";start = clock();while (clock() - start < delay);cout << "done!\a\n";return 0;}



原创粉丝点击