首页 > 解决方案 > Guarantee that a C program starting at exactly the same time as a Python program will have the same integer time value

问题描述

I am currently writing code involving piping data from a C program to a Python program. This requires that they both have exactly the same time value as an integer. My method of getting the time is:

However, I am getting inconsistencies in output leading me to believe that this is not resulting in the same value. The C program takes < 0.001s to run, while:

time ./cprog | python pythonprog.py

gives times typically looking like this:

    real    0m0.043s
    user    0m0.052s
    sys     0m0.149s

Approximately one in every 5 runs results in the expected output. Can I make this more consistent?

标签: pythonctime

解决方案


Not a solution - but an explanation.

When starting python (or other interpreted/VM langauge), there is usually startup cost associated with read and parsing the many modules that are needed. Even a small Python program like 'print 5' will will perform large number of IO.

The startup cost will delay the initial lookup for the current time.

From strace output, invoking a python code will result in >200 open calls, ~ (f)stat, >20 mmap calls, etc.

strace -c python prog.py
% time     seconds  usecs/call     calls    errors syscall
------ ----------- ----------- --------- --------- ----------------
 31.34    0.000293           1       244       178 openat
  9.84    0.000092           1       100           fstat
  9.20    0.000086           1        90        60 stat
  8.98    0.000084           1        68           rt_sigaction
  7.81    0.000073           1        66           close
  2.14    0.000020           2         9           brk
  1.82    0.000017           9         2           munmap
  1.39    0.000013           1        26           mmap
  1.18    0.000011           2         5           lstat
...

推荐阅读