调用一段时间的函数

我想要打一个电话 – 要么是一个函数调用,要么在一段时间内做一些条件…通常是10 – 20秒。

我会得到一些用户input的时间量,并做到这一点…

什么是在Linux / Unix系统上使用的正确function?

gettimeofday似乎是要走的路…或者time_t time(time_t * t)…似乎很简单。 什么是首选?

那么这是你想要的东西吗? 这将在接下来的20秒内重复调用myfunc()。 所以可以做1次调用(如果myfunc至少要运行20秒)或数百次调用(myfunc()需要几毫秒才能完成):

#include <time.h> void myfunc() { /* do something */ } int main() { time_t start = time(NULL); time_t now = time(NULL); while ((now - start) <= 20) { myfunc(); time_t now = time(NULL); } } 

可能值得问一下你最终想达到什么目的。 如果这是用于分析(例如,函数f执行的平均时间是多少),那么您可能需要查看其他解决方案 – 例如,使用gcc给您的内置分析(在构建代码时使用“ -pg“选项),并使用gprof进行分析。

这可以这样做

 #include <ctime> /* your function here */ int main() { double TimeToRunInSecs = ...; clock_t c = clock(); while(double(clock()-c)/CLOCKS_PER_SEC < TimeToRunInSecs) { myFunc(); } } 

标准clock()函数从进程启动中返回SOMETHING的数量。 在一秒钟有CLOCK_PER_SEC SOMETHINGs 🙂

HTH

我可以做一个

time_t current_time = time(0);

并衡量这一点…但有一个首选的方式…主要是这是一个最佳做法的一种问题….

X

几件事..

如果你想确保这个函数需要一个Time X来完成,不管函数中的实际代码花了多长时间,可以这样做(高度伪代码)

 class Delay { public: Delay(long long delay) : _delay(delay) // in microseconds { ::gettimeofday(_start, NULL); // grab the start time... } ~Delay() { struct timeval end; ::gettimeofday(end, NULL); // grab the end time long long ts = _start.tv_sec * 1000000 + _start.tv_usec; long long tse = end.tv_sec * 1000000 + end.tv_usec; long long diff = tse - ts; if (diff < _delay) { // need to sleep for the difference... // do this using select; // construct a struct timeval (same as required for gettimeofday) fd_set rfds; struct timeval tv; int retval; FD_ZERO(&rfds); diff = _delay - diff; // calculate the time to sleep tv.tv_sec = diff / 1000000; tv.tv_usec = diff % 1000000; retval = select(0, &rfds, NULL, NULL, &tv); // should only get here when this times out... } } private: struct timeval _start; }; 

然后在你的函数的顶部定义一个Delay类的实例来延迟 – 应该做的伎俩…(这个代码是未经测试的,可能有错误,我只是键入它给你一个想法..)