Last active
May 20, 2018 01:54
-
-
Save corvofeng/10e7fcd05bb9395f679da5129c8b82d2 to your computer and use it in GitHub Desktop.
最近在写程序时, 误用clock()函数作为定时器, 导致最后结果出现了问题, 这里, 我贴一下自己的实验过程
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
*======================================================================= | |
* Filename:clock_test.c | |
* | |
* Version: 1.0 | |
* Created on: May 20, 2018 | |
* | |
* Author: corvo | |
* | |
* gcc clock_test.c -o clock_test -lm | |
* | |
* 首先明确, clock函数返回的是程序使用的处理器时钟. | |
* 所以clock更加适合用来统计程序运行时间, 而作为程序定时器则是全然不准的. | |
* | |
* 以下面的程序为例, | |
* 如果你使用sleep, 此时并没有消耗CPU时钟, 那么clock的计数值就会很低, | |
* 除非你真正的运行计算任务来消耗CPU时钟. | |
* | |
*======================================================================= | |
*/ | |
#include <stdio.h> | |
#include <unistd.h> | |
#include <time.h> | |
#include <math.h> /* sqrt */ | |
int frequency_of_primes (int n) { | |
int i,j; | |
int freq=n-1; | |
for (i=2; i<=n; ++i) for (j=sqrt(i);j>1;--j) if (i%j==0) {--freq; break;} | |
return freq; | |
} | |
// 下面这个函数使用了clock_gettime, 可以正常进行计数器功能 | |
void simple_timer() { | |
struct timespec start, finish; | |
double elapsed; | |
clock_gettime(CLOCK_MONOTONIC, &start); | |
sleep(2); | |
clock_gettime(CLOCK_MONOTONIC, &finish); | |
elapsed = (finish.tv_sec - start.tv_sec); | |
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0; | |
printf("Now we get %fs\n", elapsed); | |
} | |
int main(int argc, char *argv[]) | |
{ | |
clock_t start = clock(); | |
// 这里不可以使用sleep函数, sleep时时钟不会 | |
// sleep(2); | |
// Get clock 0.000022 | |
frequency_of_primes(999999); | |
// Get clock 1.579848 | |
clock_t end = clock(); | |
printf("Get clock %fs\n", (double)(end - start) / CLOCKS_PER_SEC); | |
simple_timer(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment