views:

361

answers:

4

I have a read function in a module.

If I perform that function simultaneously I need to timestamp it.

How do I do this?

+3  A: 

#!/usr/bin/env python

import datetime

def timestampit(func):
    def decorate(*args, **kwargs):
        print datetime.datetime.now()
        return func(*args, **kwargs)
    return decorate

@timestampit
def hello():
    print 'hello'

hello()

# Output:
# $ python test.py 
# 2009-01-09 11:50:48.704584
# hello
Swaroop C H
I am a beginner in Python.Please dont mind of my question.Can you please explain what is happening ,Swaroop???
@rejinacm, We are using decorators, you can [read about it in this introduction](http://www.artima.com/weblogs/viewpost.jsp?thread=240808).
Swaroop C H
+6  A: 

I'll offer a slightly different approach:

import time

def timestampit(func):
    def decorate(*args, **kwargs):
        decorate.timestamp = time.time()
        return func(*args, **kwargs)
    return decorate

@timestampit
def hello():
    print 'hello'


hello()
print hello.timestamp

time.sleep(1)

hello()
print hello.timestamp

The differences from Swaroop's example are:

  1. I'm using time.time() and not datetime.now() for a timestamp, because it's more suitable for performance testing
  2. I'm attaching the timestamp as an attribute of the decorated function. This way you may invoke and keep it whenever you want.
Eli Bendersky
He is asking about simultaneous calls of the function. With this approach the slightly later call will overwrite the timestamp from the call before.
unbeknown
Yes, but this is an intentional example with the same function. He can decorate two different functions. And frankly what does simultaneous mean ??
Eli Bendersky
Right, I'm pretty sure he did't talk about threads or other parallelization techniques. But in absence of an other explanation of what "simultaneous" might mean, I thought, I would mention it here.
unbeknown
A: 

If you're interested, there's a wealth of information about decorators on the python wiki.

Jon Cage
A: 

Some example code by Terik Ziade

(more polished version, which uses timeit module, can be found in his recent book Expert Python Programming)

Mekk