sysconf(_SC_CLK_TCK) 它返回什么?

问题描述 投票:0回答:3

我试图理解各种sysconf宏。我编写了如下程序。

int main()
{
    fprintf(stdout, "No. of clock ticks per sec : %ld\n",sysconf(_SC_CLK_TCK));
    return 0;
}

我得到的结果总是 100。我在主频为 2.93GHz 的 CPU 上运行它。数字 100 究竟意味着什么?

c linux kernel
3个回答
25
投票

这只是每秒的时钟滴答数,在您的情况下,内核配置为每秒 100 个时钟(或 100Hz 时钟)。


3
投票

每秒的时钟滴答数可以通过

sysconf
系统调用找到,

printf ("_SC_CLK_TCK = %ld\n", sysconf (_SC_CLK_TCK));

每秒时钟滴答的典型值为 100。也就是说,在这种情况下,每 10 毫秒或 0.01 秒有一个时钟滴答。要将时间返回的

clock_t
值转换为秒,必须除以每秒的时钟滴答数。使用时间和
sysconf (_SC_CLK_TCK)
系统调用的示例程序是,

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <time.h> 
#include <sys/times.h> 

int main ()
{
    clock_t ct0, ct1; 
    struct tms tms0, tms1; 
    int i; 

    if ((ct0 = times (&tms0)) == -1) 
        perror ("times"); 

    printf ("_SC_CLK_TCK = %ld\n", sysconf (_SC_CLK_TCK)); 

    for (i = 0; i < 10000000; i++) 
        ; 

    if ((ct1 = times (&tms1)) == -1) 
        perror ("times"); 

    printf ("ct0 = %ld, times: %ld %ld %ld %ld\n", ct0, tms0.tms_utime,
        tms0.tms_cutime, tms0.tms_stime, tms0.tms_cstime); 
    printf ("ct1 = %ld, times: %ld %ld %ld %ld\n", ct1, tms1.tms_utime,
        tms1.tms_cutime, tms1.tms_stime, tms1.tms_cstime); 
    printf ("ct1 - ct0 = %ld\n", ct1 - ct0); 
}

来源:

http://www.softprayog.in/tutorials/linux-process-execution-time


0
投票

我认为

_SC_CLK_TCK
是Linux时间测量的粒度,而不是像它可能出现的那样的CPU时钟频率。引用来自 softprayog.in 的代码的 answer 可以通过一些更改更清楚地显示 _SC_CLK_TCK
 的使用。当必须测试慢速函数时会增加价值,因为仅使用计时器并不能澄清计算时间是否花费在其他地方:

#include <stdio.h> #include <unistd.h> #include <sys/times.h> #include <errno.h> int main ( int argc, char* argv[] ) { clock_t clockTckCt0, clockTckCt1; struct tms usedTckCts0, usedTckCts1; float clockTckDelta_ms, usedTckDelta_ms, clockTicksPerMillisecond; int i, j; // For a normal _SC_CLK_TCK of 100, this will be 0.1 clockTicksPerMillisecond = 1000.0f / sysconf( _SC_CLK_TCK ); errno = 0; clockTckCt0 = times( &usedTckCts0 ); if ( errno ) return errno; // Busy work... for ( i = 0; i < 100000000; i++ ) { ; } errno = 0; clockTckCt1 = times( &usedTckCts1 ); if ( errno ) return errno; clockTckDelta_ms = (clockTckCt1 - clockTckCt0) * clockTicksPerMillisecond; usedTckDelta_ms = usedTckCts1.tms_utime - usedTckCts0.tms_utime; usedTckDelta_ms += usedTckCts1.tms_stime - usedTckCts0.tms_stime; usedTckDelta_ms += usedTckCts1.tms_cutime - usedTckCts0.tms_cutime; usedTckDelta_ms += usedTckCts1.tms_cstime - usedTckCts0.tms_cstime; usedTckDelta_ms *= clockTicksPerMillisecond; // If this were a multi-threaded load on a multi-core CPU, the CPU use // could show as much as 400% on a quad core printf ( "time elapsed: %.1f ms, cpu time used by this process: %.1f ms, ratio: %.2f%%\n", clockTckDelta_ms, usedTckDelta_ms, 100.0f * usedTckDelta_ms / clockTckDelta_ms ); }
    
© www.soinside.com 2019 - 2024. All rights reserved.