如果我有以下代码:
clock_t t;
t = clock();
//algorithm
t = clock() - t;
t
等于运行程序的滴答数。这与 CPU 时间相同吗?
如何比较两种算法的 CPU 时间?
操作系统:Debian GNU/Linux
clock()
来测量 CPU 时间,但并非所有实现都这样做。特别是微软在VS中的实现在多线程运行时不计算额外的时间,或者在程序的线程休眠/等待时计算较少的时间。
另请注意,
clock()
应测量整个程序使用的 CPU 时间,因此,虽然将测量 //algorithm
中的多个线程使用的 CPU 时间,但不属于 //algorithm
的其他线程也会被计算在内。
clock()
是标准中指定的唯一测量 CPU 时间的方法,但是肯定还有其他特定于平台的方法来测量 CPU 时间。
std::chrono
不包含任何用于测量 CPU 时间的时钟。它只有一个与系统时间同步的时钟、一个相对于实时以稳定速率前进的时钟以及一个“高分辨率”但不一定测量 CPU 时间的时钟。
#include <ctime>
std::clock_t c_start = std::clock();
// your_algorithm
std::clock_t c_end = std::clock();
long_double time_elapsed_ms = 1000.0 * (c_end-c_start) / CLOCKS_PER_SEC;
std::cout << "CPU time used: "
<< time_elapsed_ms
<< " ms\n";
当然,如果你以秒为单位显示时间:
std::cout << "CPU time used: "
<< time_elapsed_ms / 1000.0
<< " s\n";
使用 pthread 执行此操作的非标准方法是:
#include <pthread.h>
#include <time.h>
timespec cpu_time()
{
thread_local bool initialized(false);
thread_local clockid_t clock_id;
if (!initialized)
{
pthread_getcpuclockid(pthread_self(), &clock_id);
initialized = true;
}
timespec result;
clock_gettime(clock_id, &result);
return result;
}
补充:更标准的做法是:
#include <sys/resource.h>
#include <stdio.h>
int main(int argc, char* argv[])
{
struct rusage r;
getrusage(RUSAGE_SELF, &r);
printf("CPU usage: %d.%06d\n", r.ru_utime.tv_sec, r.ru_utime.tv_usec);
}
C++ 有一个 chrono 库。请参阅 http://en.cppreference.com/w/cpp/chrono。通常还存在依赖于平台的方法来获取高分辨率计时器(显然因平台而异)。
clock() 将测量 Linux 上的 CPU 时间和 Windows 上的 wall time。 要测量 Windows 中的 CPU 时间,您可以使用“processthreadsapi”:
#include <stdio.h>
#include <processthreadsapi.h>
double get_cpu_time(){
FILETIME a,b,c,d;
if (GetProcessTimes(GetCurrentProcess(),&a,&b,&c,&d) != 0){
// Returns total user time.
// Can be tweaked to include kernel times as well.
return
(double)(d.dwLowDateTime |
((unsigned long long)d.dwHighDateTime << 32)) * 0.0000001;
}else{
// Handle error
return 0;
}
}
int main () {
double begin = get_cpu_time();
// Algorithm
double end = get_cpu_time();
double elapsed = (end - begin);
return 0;
}