Best timing method in C?

前端 未结 6 984
广开言路
广开言路 2020-11-28 18:55

What is the best way to time a code section with high resolution and portability?

/* Time from here */
ProcessIntenseFunction();
/* to here. */

printf(\"Tim         


        
6条回答
  •  野性不改
    2020-11-28 19:12

    gettimeofday() will probably do what you want.

    If you're on Intel hardware, here's how to read the CPU real-time instruction counter. It will tell you the number of CPU cycles executed since the processor was booted. This is probably the finest-grained, lowest overhead counter you can get for performance measurement.

    Note that this is the number of CPU cycles. On linux you can get the CPU speed from /proc/cpuinfo and divide to get the number of seconds. Converting this to a double is quite handy.

    When I run this on my box, I get

    11867927879484732
    11867927879692217
    it took this long to call printf: 207485
    

    Here's the Intel developer's guide that gives tons of detail.

    #include 
    #include 
    
    inline uint64_t rdtsc() {
        uint32_t lo, hi;
        __asm__ __volatile__ (
          "xorl %%eax, %%eax\n"
          "cpuid\n"
          "rdtsc\n"
          : "=a" (lo), "=d" (hi)
          :
          : "%ebx", "%ecx");
        return (uint64_t)hi << 32 | lo;
    }
    
    main()
    {
        unsigned long long x;
        unsigned long long y;
        x = rdtsc();
        printf("%lld\n",x);
        y = rdtsc();
        printf("%lld\n",y);
        printf("it took this long to call printf: %lld\n",y-x);
    }
    

提交回复
热议问题