473,398 Members | 2,113 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,398 software developers and data experts.

How Can I Increase the Speed of a Large Number of Date Conversions

I am a programming amateur and a Python newbie who needs to convert
about 100,000,000 strings of the form "1999-12-30" into ordinal dates
for sorting, comparison, and calculations. Though my script does a ton
of heavy calculational lifting (for which numpy and psyco are a
blessing) besides converting dates, it still seems to like to linger
in the datetime and time libraries. (Maybe there's a hot module in
there with a cute little function and an impressive set of
attributes.)

Anyway, others in this group have said that the date and time
libraries are a little on the slow side but, even if that's true, I'm
thinking that the best code I could come up with to do the conversion
looks so clunky that I'm probably running around the block three times
just to go next door. Maybe someone can suggest a faster, and perhaps
simpler, way.

Here's my code, in which I've used a sample date string instead of its
variable name for the sake of clarity. Please don't laugh loud enough
for me to hear you in Davis, California.

dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
dateTuple = dateTuple[:3]
date = datetime.date(dateTuple[0], dateTuple[1],
dateTuple[2])
ratingDateOrd = date.toordinal()

P.S. Why is an amateur newbie trying to convert 100,000,000 date
strings into ordinal dates? To win try to win a million dollars, of
course! In case you haven't seen it, the contest is at www.netflixprize.com.
There are currently only about 23,648 contestants on 19,164 teams from
151 different countries competing, so I figure my chances are pretty
good. ;-)

Jun 8 '07 #1
6 1539
Some Other Guy <bg****@microsoft.comwrote:
vdicarlo wrote:
>I am a programming amateur and a Python newbie who needs to convert
about 100,000,000 strings of the form "1999-12-30" into ordinal dates
for sorting, comparison, and calculations. Though my script does a ton
of heavy calculational lifting (for which numpy and psyco are a
blessing) besides converting dates, it still seems to like to linger
in the datetime and time libraries. (Maybe there's a hot module in
there with a cute little function and an impressive set of
attributes.)
...
>dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
dateTuple = dateTuple[:3]
date = datetime.date(dateTuple[0], dateTuple[1],
dateTuple[2])
ratingDateOrd = date.toordinal()
There's nothing terribly wrong with that, although strptime() is overkill
if you already know the date format. You could get the date like this:
date = apply(datetime.date, map(int, "2005-12-19".split('-')))
But, more importantly... 100,000,000 individual dates would cover 274000
years! Do you really need that much?? You could just precompute a
dictionary that maps a date string to the ordinal for the last 50 years
or so. That's only 18250 entries, and can be computed in less than a second.
Lookups after that will be near instantaneous:
For that matter why not memoize the results of each conversion
(toss it in a dictionary and precede each conversion with a
check like: if this_date in datecache: return datecache[this_date]
else: ret=convert(this_date); datecache[this_date]=ret; return ret)

(If you don't believe that will help, consider that a memo-ized
implementation of a recursive Fibonacci function runs about as quickly
as iterative approach).
--
Jim Dennis,
Starshine: Signed, Sealed, Delivered

Jun 8 '07 #2
James T. Dennis wrote:
Some Other Guy <bg****@microsoft.comwrote:
>vdicarlo wrote:
>>I am a programming amateur and a Python newbie who needs to convert
about 100,000,000 strings of the form "1999-12-30" into ordinal dates
for sorting, comparison, and calculations. Though my script does a ton
of heavy calculational lifting (for which numpy and psyco are a
blessing) besides converting dates, it still seems to like to linger
in the datetime and time libraries. (Maybe there's a hot module in
there with a cute little function and an impressive set of
attributes.)
...
>>dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
dateTuple = dateTuple[:3]
date = datetime.date(dateTuple[0], dateTuple[1],
dateTuple[2])
ratingDateOrd = date.toordinal()
>There's nothing terribly wrong with that, although strptime() is overkill
if you already know the date format. You could get the date like this:
> date = apply(datetime.date, map(int, "2005-12-19".split('-')))
>But, more importantly... 100,000,000 individual dates would cover 274000
years! Do you really need that much?? You could just precompute a
dictionary that maps a date string to the ordinal for the last 50 years
or so. That's only 18250 entries, and can be computed in less than a second.
Lookups after that will be near instantaneous:

For that matter why not memoize the results of each conversion
(toss it in a dictionary and precede each conversion with a
check like: if this_date in datecache: return datecache[this_date]
else: ret=convert(this_date); datecache[this_date]=ret; return ret)

(If you don't believe that will help, consider that a memo-ized
implementation of a recursive Fibonacci function runs about as quickly
as iterative approach).

Even better do something like (not tested):

try: dateord=datedict[cdate]
except KeyError:
dateord=datetime.date(*[int(x) for x in "2005-12-19".split('-'))
datedict[cdate]=dateord
hat way you build the cache on the fly and there is no penalty if
lookup key is already in the cache.
Jun 8 '07 #3
Some Other Guy wrote:
vdicarlo wrote:
>I am a programming amateur and a Python newbie who needs to convert
about 100,000,000 strings of the form "1999-12-30" into ordinal dates
for sorting, comparison, and calculations. Though my script does a ton
of heavy calculational lifting (for which numpy and psyco are a
blessing) besides converting dates, it still seems to like to linger
in the datetime and time libraries. (Maybe there's a hot module in
there with a cute little function and an impressive set of
attributes.)
...
>dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
dateTuple = dateTuple[:3]
date = datetime.date(dateTuple[0], dateTuple[1],
dateTuple[2])
ratingDateOrd = date.toordinal()

There's nothing terribly wrong with that, although strptime() is overkill
if you already know the date format. You could get the date like this:

date = apply(datetime.date, map(int, "2005-12-19".split('-')))

But, more importantly... 100,000,000 individual dates would cover 274000
years! Do you really need that much?? You could just precompute a
dictionary that maps a date string to the ordinal for the last 50 years
or so. That's only 18250 entries, and can be computed in less than a second.
Lookups after that will be near instantaneous:
import datetime

days = 365*50 # about 50 years worth
dateToOrd = {} # dict. of date string to ordinal
....

Then there's the argument of "why bother using real dates?" I mean, all
that is necessary is a mapping of date -number for sorting. Who needs
accuracy?

for date in inp:
y, m, d = map(int, date.split('-'))
ordinal = (y-1990)*372 + (m-1)*31 + d-1

Depending on the allowable range of years, one could perhaps adjust the
1990 up, and get the range of date ordinals down to about 12 bits (if
one packs netflix data properly, you can get everything in memory).
With a bit of psyco, the above is pretty speedy.

- Josiah
Jun 8 '07 #4
vdicarlo <vd******@gmail.comwrites:
>I am a programming amateur and a Python newbie who needs to convert
about 100,000,000 strings of the form "1999-12-30" into ordinal dates
for sorting, comparison, and calculations. Though my script does a ton
of heavy calculational lifting (for which numpy and psyco are a
blessing) besides converting dates, it still seems to like to linger
in the datetime and time libraries. (Maybe there's a hot module in
there with a cute little function and an impressive set of
attributes.)
>Anyway, others in this group have said that the date and time
libraries are a little on the slow side but, even if that's true, I'm
thinking that the best code I could come up with to do the conversion
looks so clunky that I'm probably running around the block three times
just to go next door. Maybe someone can suggest a faster, and perhaps
simpler, way.
>Here's my code, in which I've used a sample date string instead of its
variable name for the sake of clarity. Please don't laugh loud enough
for me to hear you in Davis, California.
>dateTuple = time.strptime("2005-12-19", '%Y-%m-%d')
dateTuple = dateTuple[:3]
date = datetime.date(dateTuple[0], dateTuple[1],
dateTuple[2])
ratingDateOrd = date.toordinal()
>P.S. Why is an amateur newbie trying to convert 100,000,000 date
strings into ordinal dates? To win try to win a million dollars, of
course! In case you haven't seen it, the contest is at www.netflixprize.com.
There are currently only about 23,648 contestants on 19,164 teams from
151 different countries competing, so I figure my chances are pretty
good. ;-)
I can't help noticing that dates in 'yyyy-mm-dd' format are already sortable
as strings.

>>'1999-12-30' '1999-12-29'
True

depending on the pattern of access the slightly slower compare speed _might_
compensate for the conversion speed. Worth a try.

Eddie
Jun 8 '07 #5
Many thanks for the lucid and helpful suggestions. Since my date range
was only a few years, I used Some Other Guy's suggestion above, which
the forum is saying will be deleted in five days, to make a dictionary
of the whole range of dates when the script starts. It was so fast it
wasn't even worth saving in a file. Made the script a LOT faster. I
guess two thousand function calls must be faster than 200 million?
Like maybe a hundred thousand times faster?

I also benefitted from studying the other suggestons. I had actually
implemented an on the fly dictionary caching scheme for one of my
other calculations. I don't know why it didn't occur to me to do it
with the dates, except I think I must be assuming, as a newbie
Pythonista, that the less I do and the more I let the libraries do the
better off I will be.

Thanks for putting me straight. As someone I know said to me when I
told him I wanted to learn Python, "the power of Python is in the
dictionaries".

Funny how long it's taking me to learn that.

Jun 9 '07 #6

"vdicarlo" <vd******@gmail.comwrote in message
news:11********************@i38g2000prf.googlegrou ps.com...
| Many thanks for the lucid and helpful suggestions. Since my date range
| was only a few years, I used Some Other Guy's suggestion above, which
| the forum is saying will be deleted in five days, to make a dictionary
| of the whole range of dates when the script starts. It was so fast it
| wasn't even worth saving in a file. Made the script a LOT faster. I
| guess two thousand function calls must be faster than 200 million?
| Like maybe a hundred thousand times faster?

Any function called repeatedly with the same input is a candidate for a
lookup table. This is a fairly extreme example.

|| I also benefitted from studying the other suggestons. I had actually
| implemented an on the fly dictionary caching scheme for one of my
| other calculations. I don't know why it didn't occur to me to do it
| with the dates, except I think I must be assuming, as a newbie
| Pythonista, that the less I do and the more I let the libraries do the
| better off I will be.
|
| Thanks for putting me straight. As someone I know said to me when I
| told him I wanted to learn Python, "the power of Python is in the
| dictionaries".
|
| Funny how long it's taking me to learn that.

Well, look at how many of us also did not quite see the now obvious answer.

Even Python's list.sort() only fairly recently gained the optional 'key'
parameter, which implements the decorate-sort-undecorate pattern and which
often obsoletes the original compare-function parameter because it saves
time by calculating (and saving) the key only once per item instead of once
each comparison.
>>import this
The Zen of Python, by Tim Peters
[snip]
Namespaces are one honking great idea -- let's do more of those!

I include lookup dictionaries in this admonition.

tjr

Jun 9 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Darsant | last post by:
I'm currently reading 1-n number of binary files, each with 3 different arrays of floats containing about 10,000 values a piece for a total of about 30,000 values per file. I'm looking for a way...
9
by: Jean-David Beyer | last post by:
When initially populating a database, it runs slower that I would have supposed. Checking here and there, especially with iostat, reveals that most of the time is spent writting the logfiles. In...
16
by: raj | last post by:
Hi, I saw it mentioned that "int" is the fastest data-type for use in C ,that is data storage/retrieval would be the fastest if I use int among the following 4 situations in a 32 bit machine with...
6
by: Dennis | last post by:
I was trying to determine the fastest way to build a byte array from components where the size of the individual components varied depending on the user's input. I tried three classes I built: (1)...
30
by: zexpe | last post by:
I have an extremely cpu/data intensive piece of code that makes heavy use of the following function: void convertToDouble(const std::string& in, double& out) { out = atof(in.c_str()); } I...
3
by: Mike Kelly | last post by:
Hi. I've built a page using standard ASP.NET 2.0 features and when I upload a large file (>20MB) to our intranet server, I get a paltry 100KB/s on our 100Mb/s LAN. Simply copying the file, I get...
11
by: Jim Lewis | last post by:
Has anyone found a good link on exactly how to speed up code using pyrex? I found various info but the focus is usually not on code speedup.
5
by: RThaden | last post by:
Hi all, I have a text file with a list of MAC addresses. Each time, my program is called it reads the last MAC address entry from the file, increases it by one, writes this new address into a 6...
0
by: Charles | last post by:
3000 rows is not a big quantity. You can load it into VC program memory, a linked list for example, and "asynchronously" load into Oracle. The connection method can be embedded SQL or ODBC. ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.