简体   繁体   中英

python time results not as expected: time.time() - time.time()

In playing around with the python execution of time , I found an odd behavior when calling time.time() twice within a single statement. There is a very small processing delay in obtaining time.time() during statement execution.

Eg time.time() - time.time()

If executed immediately in a perfect world, would compute in a result of 0.

However, in real world, this results in a very small number as there is an assumed delay in when the processor executes the first time.time() computation and the next. However, when running this same execution and comparing it to a variable computed in the same way, the results are skewed in one direction.

See the small code snippet below. This also holds true for very large data sets

import time

counts = 300000

def at_once():
  first = 0
  second = 0
  x = 0
  while x < counts:
      x += 1
      exec_first = time.time() - time.time()
      exec_second = time.time() - time.time()

      if exec_first > exec_second:
          first += 1
      else:
          second += 1


print('1sts: %s' % first)
print('2nds: %s' % second)

prints:

1sts: 39630
2nds: 260370

Unless I have my logic incorrect, I would expect the results to very close to 50:50, but it does not seem to be the case. Is there anyone who could explain what causes this behavior or point out a potential flaw with the code logic that is making the results skewed in one direction?

Could it be that exec_first == exec_second ? Your if-else would add 1 to second in that case.

Try changing you if-else to something like:

if exec_first > exec_second:
    first += 1
elif exec_second > exec_first:
    second += 1
else:
    pass

You assign all of the ties to one category. Try it with a middle ground:

import time

counts = 300000
first = 0 
second = 0 
same = 0

for _ in range(counts):
    exec_first = time.time() - time.time()
    exec_second = time.time() - time.time()

    if exec_first == exec_second:
        same += 1
    elif exec_first > exec_second:
        first += 1 
    else:
        second += 1 

print('1sts: %s' % first)
print('same: %s' % same)
print('2nds: %s' % second)

Output:

$ python3 so.py
1sts: 53099
same: 194616
2nds: 52285
$ python3 so.py
1sts: 57529
same: 186726
2nds: 55745

Also, I'm confused as to why you think that a function call might take 0 time. Every invocation requires at least access to the system clock and copying that value to a temporary location of some sort. This isn't free of overhead on any current computer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM