user2329125
user2329125

Reputation:

How do you call c macros in julia

I know you can call functions with ccall and get pointers to global symbols with cglobal. But how do you get access to macros?

For example I wan't to replicate this code

clock_t start = clock();
clock_t end = clock();
float seconds = (float)(end - start) / CLOCKS_PER_SEC;

How can I execute the CLOCKS_PER_SEC macro at the end?

Upvotes: 0

Views: 203

Answers (2)

Dan Getz
Dan Getz

Reputation: 18217

Another answer, which stays inside Julia could be (try it out):

for i=1:10
    b = 10^i
    tic()
    s = 0
    start = ccall(:clock,Clonglong,())
    for i=1:b
        s+=i
    end
    t = toq()
    stop = ccall(:clock,Clonglong,())
    if t>1.0
        println("CLOCK_PER_SEC most probably is ",10^(round(Int,log10((stop-start)/t))))
        break
    end
end

This answer assumes CLOCKS_PER_SEC is a power of 10, which seems to be universally the case. Note the for loop inside is used to waste process time and not wall time which could simply be wasted with sleep.

Upvotes: 0

Dan Getz
Dan Getz

Reputation: 18217

CLOCKS_PER_SEC is a constant defined in the standard header file time.h.

It is much better to use the timing facilities available in Julia and keep the program in one language (as the great ones intended). But if you insist, you can create the following simple C program:

#include <stdio.h>
#include <time.h>

int main(int argc, char** argv) {
    printf("%ld\n",CLOCKS_PER_SEC);
  return 0;
}

Compile it using something like gcc clocks_per_sec.c -o clocks_per_sec. And then run it from Julia using:

julia> clocks_per_sec = parse(Int,read(`./clocks_per_sec`,String))
1000000

It might be simpler to just get the number once and plug it as a constant in the Julia program assuming the system will run on the specific computer or will not be maintained for a long time with the external C dependency.

P.S. The Julia code is relevant to 0.7 version, on earlier version, use readstring(...)) instead of read(...,String).

Upvotes: 1

Related Questions