Friday, March 2, 2012

Dr. Seuss and the Decline of Western Civilization

I gave the following brief talk recently at my morning men’s group:

I’ve been asked to talk this morning about pride, and this seems like a terribly relevant topic for folks like us, who live in 21st century America. Sometimes I think that no civilization in history has ever fussed quite so much about self-esteem as ours has, or has ever encouraged such a frankly individualistic and self-centered worldview.

Still, it’s worth noting that it was nearly 2500 years ago that Aristotle said, “Pride is the crown of the virtues.” Aristotle’s model for this assertion were mythic heroes like Hector and Achilles, but we can see the fruit of his ethical position all too clearly in violence and brutality of his pupil, Alexander the Great. Christianity for a time curbed these tendencies, but they have more recently begun to roar back.  In the 19th century, the philosopher Friedrich Nietzsche went even further than Aristotle when he said, “Egoism is the very essence of a noble soul.” This perspective, that the primary goal of a human life is to assert ones own claims, is thus neither new nor entirely unique to our culture. Nevertheless, I do believe that both the extent and the rapidity with which it has come to dominate our society is worthy of comment.

I think we can make clear just how quickly and how firmly our culture has adopted a philosophy of self-centeredness by comparing two well-known books by Theodore Geisel - better known, perhaps, as Dr. Seuss. Dr. Seuss began writing children’s books back in the late 1930’s, in the run-up to World War II. In 1940, he wrote Horton Hatches the Egg, about the resolute and humble Horton, an elephant tricked into hatching an egg by a lazy and faithless “Mayzie Bird”. Expressing his determination to fulfill his promise, Horton also expressed our society’s then-dominant moral outlook with these words:

I meant what I said, and I said what I meant:
an elephant’s faithful, one hundred percent.

This is stern stuff, full of honesty, loyalty, and self-sacrificial love, and it’s not surprising that the Greatest Generation was raised on it. You don’t survive the Great Depression and World War II without a reasonably stiff backbone.

But shortly before his death in 1991, Dr. Seuss published another book that expresses a quite different perspective. The book is called Oh the Places You’ll Go!, and on every page it reflects the dramatic cultural changes that had taken place since World War II. The book is clever and witty, and I won’t deny that there’s some wisdom in it, but at its heart it seems to endorse a disconcerting self-centeredness. Instead of encouraging faithfulness and loyalty, its theme can be reduced to these words from its opening pages:

You're on your own. And you know what you know.
And you are the guy who'll decide where to go.

Nietszche and the Mayzie Bird would have nodded and approved, of course, but you have to imagine that poor faithful Horton would hardly have hardly known what to make of such an amoral egoism.
Regrettably, this perspective isn’t limited to children’s books. Try reading a typical advice column and note how much of its advice assumes that we need to think both more often and more highly of ourselves. Take a couple dozen newspaper editorials on controversial social issues, such as abortion or gay marriage, and see how rarely they advocate for an increased sense of personal humility, or commend a course of greater self-sacrifice and discipline. How many movies or TV shows have you seen in the last year which said, in effect, “You need to express yourself, be your own person, stop conforming to what other people want you to be”?

But like I said, this emphasis on claiming our own rights is hardly new. It didn’t start with Aristotle or Nietszsche, and it won’t end with either Dr. Seuss or Dear Abby. It started, in fact, in the Garden of Eden, when the serpent suggested to Eve that she might know her own good better than God.

According to Augustine, pride is “the craving for undue exaltation”. In other words, it is the desire to put ourselves first, not just before others, but most especially, before God. Now, it’s critical to remember that God created us for Himself, and that our hearts will always be restless unless they rest in Him. Our chief end is to glorify God and to enjoy Him forever; and the enjoyment and the glorification go hand in hand. The rest when we serve Him, the restlessness when we abandon Him and exalt ourselves, are not outcomes that God could change if He wanted, but are fundamental expressions of ultimate reality. To know God is to know Him as immeasurably greater than ourselves. God doesn’t demand loyalty to Himself out of any desire for self-aggrandization, as if God Himself were proud, but rather, because that is who He is, and that is who we are. God can’t make us happy without Himself anymore than water can cease to be wet.

Thus, when we become proud, we are by definition separating ourselves from God. We are refusing to know God as God, and when we refuse to acknowledge this fundamental reality, the rest of our faculties degrade in lock step. We don’t see reality as well as we did before; we don’t understand the world as well as we ought. We take things that ought to be first and make them last. We exchange the glory of the incorruptible God for corruptible images and pale imitations.

This, then, was the sin of Adam; and this was the sin of Eve. That it was an apple or some other fruit is almost incidental: the key is that they chose to know good and evil, that is, they chose to decide for themselves what would be good and what would be evil. For whatever unimaginable reason, they placed themselves in the place of God. The serpent spoke as truly as the serpent could: after eating the fruit, they were as gods: they became their own end and desire and satisfaction. This end, of course, was neither desirable nor satisfactory, for when they moved the true God out of His place, the false gods moved in.

And in this sense, as in so many others, we are the sons of Adam and the daughters of Eve. We’re on our own; we know what we know; we are the ones who’ll decide where to go. Or in other words, “Better to reign in hell than serve in heaven”. But when we affirm this creed, when we refuse to be ruled by the one true God, we discover that we are ruled instead by the false gods of sex, ambition, and money. We desire to serve only ourselves, and serve instead every intellectual or moral fashion that blows our way. And the result is the sad, tragic history of humanity that we know so well. All the wars and nearly all the famines, all the divorces and affairs, all the rapes and genocides, every terrible crime and every tawdry scandal has its origin in this ineluctable turn toward ourselves and away from God.
There is, of course, only one rescue from this fate, and that is the cross. For our pride can only be moved from its seat at the center of our souls when we know God for who He truly is. And it is in the cross that we see God most truly and most completely. George MacDonald said,

When he died on the cross, he did that, in the wild weather of his outlying provinces, in the torture of the body of his revelation, which he had done at home in glory and gladness.

The only and final cure for our pride is to constantly remind ourselves that the God who dwells in unapproachable light became a human being so that He could light our way for us; that the author of life suffered death out of love for us; that the Creator let His creation crucify Him. If pride, by definition, cuts us off from knowing God, then knowing God, by definition, will begin to heal us of our pride. And to know God, we must know Jesus; and to know Jesus, we must pass under the shadow of the cross.

I wish I had better advice; and if I were less proud myself, I suspect I would. One of the side-effects of humility is that you can understand the world better. But in the meantime, I can only point you - I can only point myself - towards the cross. And given all the pressure we encounter in our culture to move in exactly the opposite direction, we can hardly do this too early or too often.

Sunday, February 12, 2012

Evangelicals and Global Warming (Part 1)

I visited my parent’s church today. It’s a very Pentecostal church, and while I haven’t been particularly Pentecostal for many years now, there are many things about the church that I admire. First among these is its well established and effective ministry with recovering alcoholics and drug users. It brings a smile to my face when I think about how many folks once sitting in jail cells are now sitting in pews and shouting hallelujah. I can imagine that first century Christians once nudged each other and said, “See her? She was possessed by seven demons before Jesus cast them out.” I’ll often hear similar comments in my parents’ church: as folks pass by, they’ll say something like, “See him? Before he got saved, he was sleeping under a van down by the river.” Or, “That guy over there? He was selling drugs out of a drive-through window.” If comments like these strike you as condescending, I’d venture to say that you probably don’t know Evangelicals very well.

The sermon this morning was solid, and gave me a lot to chew on. It took Romans 12:1-2 as its text, which says, “Do not conformed to this world, but instead be transformed by the renewing of your mind.” That seemed especially relevant in light of my renewed skepticism of the mainstream media’s portrayal of social and religious issues. As I mentioned in my last post, recent events have driven home to me the importance of a pretty strong filter when the media tries to cover social conservatives.

Still, I was taken aback when the pastor said (I’m paraphrasing from memory, but this is pretty close):

You’ve probably heard a lot about global warming. But that’s just another example of how the media doesn’t tell us the truth. Global warming is just one more big hoax that the media has tried to pull over on us.

My wife and I looked at each other, to make sure we’d actually heard what we thought. I was pretty surprised, both that this pastor (whom I like and respect) would believe this, but even more that he’d choose to bring it up in a sermon. It had nothing to do with the Gospel, and worse, he made it seem like it did. It sent the unmistakable message that if you want to be a good Christian, you ought to believe that global warming is a scam. And that’s a shame, for more reasons than I can begin to count.

Still, because I’ve recently expressed my extreme disappointment with liberals on the matter of religious liberty, it seemed an appropriate time to blog about how frustrated I am with conservative positions on the environment, particularly with respect to global warming. I know lots of folks conservatives who would agree with my parent’s pastor, that climate change is a hoax. And I’m really, really curious about why this is this so.

I’ll start by saying that it’s clearly not because they’ve made an independent and sufficient evaluation of the evidence, and have rejected it as inadequate.  The plain fact of the matter is that nobody I know personally (and this obviously includes me) is anything like qualified enough to offer an authoritative opinion on the science behind scientists’ claims regarding climate change. Yes, I suppose most of us have a cursory understanding of the physics of global warming: CO2 and methane act as “greenhouse gases”, trapping more warmth in the atmosphere, thus raising temperatures worldwide. Some of us may have observed the retreat of glaciers with our own eyes, most of us have read about the increased rate of polar ice melting, and probably a good number have read mainstream summaries of the science behind it (this piece by The Economist is probably the best). But the fact remains that the earth’s climate is composed of innumerable systems whose interactions are mind-bogglingly complex, and the measurements, the math, and the models that real climate scientists use to predict their behavior are only slightly less so. I could spend the next four or five years doing nothing but studying climate change, and I’d barely be qualified to comment on the quality of a few journal articles, and still less on any overarching conclusions that real scientists might reach after having critically digested thousands of them. I simply don’t know enough; and neither does anybody else that I know. There are roughly 7 billion humans on this planet, and maybe a thousand of them possess the knowledge and experience that I freely admit I lack. (This study, for instance, was able to identify 1,372 individuals actively publishing in the field of climate change.) In other words, folks qualified to comment authoritatively on climate science are not just one in a million: they’re quite literally one in seven million. The vast majority of folks who reject global warming, as well as the vast majority of folks who accept it, are doing it for other reasons entirely.

And here’s another red herring. Your typical climate change skeptic doesn’t reject the idea of global warming because the folks who are qualified to judge haven’t made up their minds. If you want to know how convincing the evidence is for climate change, don’t start with this Wikipedia article (on the physics), but with this one (on the consensus opinion among scientists). There’s a lot of data in there, but this gives you a feel for its conclusions:

The predominant scientific opinion on climate change is that the Earth's climate system is unequivocally warming and it is more than 90% certain that humans are causing it . . . No scientific body of national or international standing has maintained a dissenting opinion . . . 97–98% of the climate researchers most actively publishing in the field support the tenets of ACC (Anthropogenic Climate Change) outlined by the Intergovernmental Panel on Climate Change.

In other words, there’s a consensus. I have some reasonable idea of what a consensus looks like, and trust me, that looks like one. And yet some 50% of Americans reject it. Why?

Well, I’ve got a theory about that, but it’ll have to wait until my next post.

Friday, February 10, 2012

Discovering What It’s Like To Be a Partisan

Most of my life, I’ve been a political moderate. My father is a Rush Limbaugh Dittohead, his father before him was a Yellow Dog Democrat, but I’ve never felt particularly comfortable in either strongly liberal or strongly conservative circles. I’m a registered Democrat mostly because, back in college, the guy doing the voter registration drive was pushing very hard for me to register as a Republican. But since then, on both issues and candidates, I’ve sometimes favored the Republicans, sometimes the Democrats. And in political discussions, I’ve generally found that it’s easier for those discussions to be interesting and productive when the person on the other side isn’t swayed by party politics, and isn’t trying to ascribe unworthy motives to the other side while trying to pretend that they themselves are pure as the driven snow. My default position when it comes to controversies is to be fairly sober-minded, to try to see both sides of the picture, to be realistic about my own and others’ motives, and not to claim more for an argument than it really warrants. As you can imagine, this makes me a pretty bad Democrat, and probably an even worse Republican. My glee at the rise and ungainly fall of Herman Cain, Newt Gingrich, Michelle Bachmann, and Rick Perry has been anything but seemly. I’m annoyed at the inability of our congressional representatives to work together, and if there were an intelligent candidate somewhere in the political middle, ready both to cut spending and raise taxes to fix our fiscal woes, he or she would find it difficult to not get my vote.

However, several recent events have upended a great deal of my self-satisfied centrism. First, in what could only have been a cynical election year ploy to excite his base, Obama decided to make the Catholic Church pay for contraceptives, sterilization, and abortifacients, in an obvious violation of several hundred years of American jurisprudence, along with the Religious Freedom Restoration Act, not to mention the First Amendment. (And of course, it turns out that this did excite the base: but the wrong one.) Second, the Susan G. Komen Foundation first dropped their support of Planned Parenthood, and in the ensuing uproar, re-established it, their hand having been forced by the media’s blatantly one-sided coverage of the move.  And finally, when I pointed these things out to friends, and expressed my astonishment, I was repeatedly met with either blank stares or outright hostility. Folks simply didn’t get why I found these two things – the Obama administration’s trampling of the First Amendment, and the news media’s blatantly biased reporting on Susan G. Komen – so objectionable. And that shocked me. After all, if someone thought that it was wrong for the government to force a particular moral viewpoint on a woman carrying a child, shouldn’t they mutatis mutandis think that it was wrong for the government to force a particular moral viewpoint on Roman Catholics? But apparently they didn’t see any problem with that sort of government intrusion.

More than that, though, my arguments with them put me in a very odd position. I dislike the smell of partisan politics intensely. Nothing is so likely to turn me off in a debate as the realization that the other person not just thinks he’s right, but is convinced that that anyone with a different perspective is operating in bad faith and with impure motives. But that’s exactly what I’m convinced has happened in these two instances. Obama is an expert on Constitutional law: there’s no way that he couldn’t have realized that the HHS decision was a blatant violation the First Amendment (especially after taking a 9-0 shellacking from the Supreme Court on a closely related issue in Hosanna-Tabor just two weeks prior). The media prides itself on its objectivity: but take a look at this interview by Andrea Mitchell, and see if you think there’s any reasonable way you could describe it as fair and balanced.

The result is that I’ve started to feel quite differently about the Republicans, and all the nasty things they’ve been saying about the Obama administration. The strong emotions animating the Tea Party have been even more of a turn-off to me than the actual positions for which they’re advocating. But now that I’ve found myself backed into a political corner, it turns out that I’m suddenly as angry as, well, a Tea Party conservative. I’m unbelievably pissed-off that the Obama administration has decided that the ideology of secularism gets to operate from a privileged position: that our country is no longer pluralist, but actively and specifically secular: that I’m welcome to my religious beliefs only so long as they extend no further than the door of my church. The logic of the Obama administration and its defenders, that public expressions of religious beliefs must always give way to the power of the state, is astonishingly similar to that of the Chinese government. This is a big hairy deal, in other words, and it represents a breathtaking invasion by the federal government into the realm of ultimate truth. It makes me angry to think about it. It’s not right, and Obama should have known better. The realization that he actually thinks this way has revealed a yawning, probably unbridgeable gap between his worldview and mine. He can talk about his respect for religion all he wants: but when it comes right down to it, it’s pretty clear that he doesn’t respect any religion so long as it insists upon actual truth claims about the fundamental nature of God, humanity and the world (in other words, all of them). I will not vote for any president who thinks that way, and I’m going to be a damned sight more suspicious of anything he says going forward.

As a side note, I was gratified to hear that as of this morning, Obama has more-or-less backed down, and is offering a compromise. But in the spirit of my newfound hermeneutic of suspicion, it’s worth pointing out that in his press conference, he baldly lied about the state of the rule-making process. The proposed compromise was not, as he portrayed it, a “speeding up” of a process already under way, but an actual change in the actual rule, a political volte-face after realizing that he’d just managed to push a whole bunch of fence-sitters like myself firmly into the waiting arms of his conservative opponents. And it’s also worth noting that the changes he has proposed seem to be purely verbal: see this analysis, which calls it “economic nonsense”; or this one, or this, which wonder how insurance companies could possibly avoid using premiums from their Catholic clients to pay for contraceptive coverage. As Robert Miller puts it:

Under the old rule, the employer had to pay for abortion-inducing drugs, sterilizations, and contraception. Under the new rule, the employer has to pay for abortion-inducing drugs, sterilizations, and contraception, but President Obama will say that it doesn’t, and we’ll believe him. That fixes everything. And to think, some people accuse President Obama of empty rhetoric.

That’s the sort of wonderfully snarky comment that would have gotten my dander up in the old days (i.e., two weeks ago), but sounds pretty good to me right now.

Moving on, when you layer the Susan G. Komen debacle onto the contraception controversy, it’s made me increasingly suspicious of anything the media has to say as well. I’ve found myself reading a variety of conservative blogs that critique the media’s portrayal of religion, and I’m a little astonished at how much sense they make. You can make the case (as liberals often do) that the mass media is owned by corporations, and hence are likely to present a conservative slant on economic issues. That may or may not be the case: but there’s no remaining doubt in my mind which direction the media leans when covering social and religious issues. This bias shows up in a thousand subtle and blatant ways, and ranges from the scare quotes around “religious liberty” in the third paragraph of this article, to the numerous mistakes of fact in this article, and the decision by the Dallas Morning News to feature a dozen protesters of Susan G. Komen’s decision on the front page, after having completely ignored an 8000-person March for Life the previous month.

So here’s the first thing. Like I said, I’m angry at Obama, and I’m newly suspicious of the news media. I’m in no mood to compromise, and right now, I’d love to see Obama filing for unemployment because of his attempted betrayal of the First Amendment. And I guess that makes me a conservative.

But here’s the other thing. For perhaps the first time in my life, I understand what a political partisan feels like. I now know what it means to be angry and frustrated, because you’re so convinced that you’re right and that your opponents are mulish and stubborn miscreants. And I know that folks on both sides feel like that. I’m able to understand a great deal of why folks on both the right and the left respond the way they do to each other. I sympathize with the partisans. I get it now. I feel their pain. And I guess that makes me a liberal.

Sunday, January 15, 2012

The Joys of Parenting

It started Thursday night. I've been fighting off the same chest cold that sent Calista to the doctor's office New Year’s Day, so before I went to bed, I took a couple NyQuil to help me sleep. About 1:00 am, I woke out of a drug-fogged sleep to find our four-year-old son Caedmon crawling into our bed. That wasn't unprecedented, but it's not normal either. I was groggy enough that I decided to cut him some slack, so I put up with him squirming and kicking me for 15 minutes or so before finally deciding that no, he had to go back to his own bed. So I picked him up and carried him back to his room. I was setting him down into his bunk bed when I noticed a strong sour smell in the air, and simultaneously felt my hands plunge into a wet, sticky substance covering his blankets. My brain took a few seconds to put it all together and draw some conclusions. Then I sighed and picked him up and carried him back into our room. We made a bed for him on the floor, got a bowl from the kitchen, and put him down, hoping that would be the end of it.

About 20 minutes later, we were awoken again, to the sound of Caedmon gagging. Most of it made it in the bowl, but by no means all of it. More cleanup and consoling. Then something like sleep, more gagging, more cleanup, more consoling. This repeated itself all night long, every 20 minutes or so, until about 5:00 am, when Caedmon finally managed to get to sleep and stay asleep. About the same time, I removed myself to the couch downstairs, and got an hour or so of rest.

When we woke up, we let Caedmon continue to sleep in our bed, and Galena began cleaning his room. Our one-year-old daughter Calista wasn't making any noise, so we let her sleep, while I tried to entertain our two-year-old son, Brendan. By 8:30 or so, though, Galena decided that she really needed to check on Calista. When she opened the door, she got a full whiff: turns out Calista had been having the same troubles, but had suffered them all in complete silence. (We even had the baby monitor on!) So her crib, her blankets, and her hair was encrusted with not-quite-dried puke. Calista herself was surprisingly calm about the whole thing, and gave us a big grin as we gingerly tried to extract her from the Crib of Dried Vomit.

After that, Friday and Friday night passed more-or-less without event. On Saturday morning, we thought we'd seen the worst of it, and since the kids were begging to go outside and play in the snow, we got them dressed and spent some time outdoors. (Caedmon discovered that it's painfully tricky to ride your bike in the snow; Brendan and Calista discovered, once again, that your hands get cold and hurt when you play in the snow and refuse to wear gloves.)

But Saturday afternoon, Calista started having a variety of diarrhea episodes, including at least one "Level 3 Containment Failure" (I'll leave the exact definition of that to your imagination). And then Galena started looking green around the gills. And then she threw up. And then the other end as well. Rinse and repeat.

So Galena took herself to bed, while I did my best to entertain the kids. Caedmon and Calista were definitely feeling better, but were still a little stunned after their run-in with the Stomach Bug That's Going Around. Brendan seemed to have a stainless steel immune system, however, and wasn't going to let anything slow him down. (And you have to remember, through all this, that I've got a cold too, and periodically feel like I'm about to hack up a lung.) When evening rolled around, I finally got the kids fed and down to bed, and all seemed quiet. So I checked in with Galena, who was still in bed, and then left for Bellevue, for a movie night with some friends that had been long planned (and for which I was supposed to supply the movie).

I got a call from a groggy-sounding Galena around 8:30. "Brendan just threw up," she said, sounding on the verge of tears. "Can you come home?" By 9:00 pm or so, I was thus available to make myself the target for Brendan's third heave of the evening. After several more abortive attempts to get Brendan to sleep, I gave up, and for an hour or two, he sat on my lap with a bowl in his hands. We passed the time by watching extreme skiing videos off of YouTube (at Brendan's request). We'd pause the video - or sometimes not - whenever Brendan started heaving, then I'd wipe his mouth, and we'd start watching the video again. It was oddly bonding. By midnight, the worst had passed, and I put him to bed.

I should note that during all this, my side of the bed had gotten nailed with at least one round, so I elected to spend the rest of the night in the guest bed in the library. Galena's side was relatively clean, and more than that, she was too tired to care.

I got up around 7:30 this morning to find Brendan and Caedmon in great spirits: they weren't up to the Running and Chasing Game, precisely, but they were quarreling normally and demanding books and juice and videos. But by 9:00 am, when Calista still hadn't made any noise, I decided to check on her. Turns out that (once again) she'd been having the same trouble as everyone else, but (also once again) hadn't complained to let anyone know about it. The carpet around her crib, her bedding, her hair, and the outside of her pajamas were covered with one particularly noxious substance; the inside of her pajamas, and most of her body, was covered with a different one, surprisingly similar in texture and smell, and equally objectionable. Even after I gave Calista a shower, Galena was still combing unidentified chunks out of her hair.

That brings us up to the present. I'm the only one who hasn't gotten the bug yet, but I can feel it circling warily at a distance, like a pack of wolves preparing for the attack. We've basically decided that all the normal household rules and routines are out the window. The kids are watching videos and drinking juice and eating pretty much whenever and whatever they want. Galena informs me that Calista has just fallen asleep in the hallway. Brendan and Caedmon have scattered a box of paper clips around my office, and I can barely bring myself to care. Civilization and discipline has given way to raw survival.

Wish us luck.

Friday, November 4, 2011

My favorite C# micro-optimizations #2: 1D Arrays

This is my second post on my favorite C# micr0-optimizations. Everything I said in the first post applies to this one as well, namely, don’t optimize until you know that you need to; and spend most of your optimization budget optimizing the algorithms, rather than figuring out which way to access an array is faster.

That said, this was a surprise to me: jagged arrays (e.g., arrays of arrays) are much faster than rectangular arrays: but indexed access into a 1D array is faster yet.

In other words, this is relatively slow:

   1:  for (int x = 0; x < size1; x++)
   2:  {
   3:      for (int y = 0; y < size2; y++)
   4:      {
   5:          result = twoDArray[x, y];
   6:      }
   7:  }

This is significantly faster:

   1:  for (int x = 0; x < size1; x++)
   2:  {
   3:      for (int y = 0; y < size2; y++)
   4:      {
   5:          result = jaggedArray[x][y];
   6:      }
   7:  }

But this is the fastest:

   1:  for (int x = 0; x < size1; x++)
   2:  {
   3:      for (int y = 0; y < size2; y++)
   4:      {
   5:          result = oneDArray[x * size2 + y];
   6:      }
   7:  }

Benchmark results on my machine (1000 iterations through a 1000x1000 array):

2DArrayTest action completed: iteration = 5, completionTime = 3111, averageCompletionTime = 3101.400
JaggedArrayTest action completed: iteration = 5, completionTime = 2283, averageCompletionTime = 2256.000
1DArrayTest action completed: iteration = 5, completionTime = 1698, averageCompletionTime = 1638.800

It’s also very much worth noting that the order in which the iteration happens is important. Sequential memory access is faster than purely random memory access, most likely because data is fetched from main memory to the CPU’s cache in chunks, so that subsequent sequential reads are from cache.

In other words, if instead of this at the center of each loop:

result = jaggedArray[x][y];
result = twoDArray[x, y];
result = oneDArray[x * size2 + y];

We switch the order of the indexes, so that memory is accessed out-of-order (this is called “diagonal access”):

result = jaggedArray[y][x];
result = twoDArray[y, x];
result = oneDArray[y * size1 + x];
Then the tests take more than twice as long:

JaggedArrayTest action completed: iteration = 5, completionTime = 7499, averageCompletionTime = 7676.400
2DArrayTest action completed: iteration = 5, completionTime = 6790, averageCompletionTime = 6818.600
1DArrayTest action completed: iteration = 5, completionTime = 5862, averageCompletionTime = 5883.200

It’s interesting that in a diagonal access pattern, rectangular arrays are indeed faster than jagged arrays: but one-dimensional arrays are still the fastest.

Thursday, November 3, 2011

My favorite C# micro-optimization #1: Buffer.BlockCopy()

So a caveat first-off. Micro-optimizations are evil. You almost never need them. You can live the vast majority of your life as a programmer and never use them; and most of the time you use them, you’re going to use them incorrectly. If your program is running slow, you’ll almost never find some tiny little micro-optimization that will fix it.

But there are times when they’re handy, and with all the work I’ve been doing the last couple years on a custom Silverlight media stack, I’ve had a number of opportunities to learn about how to speed up code that gets called thousands of times each second. This series of articles is the result of that experience.

And my first suggestion is to use Buffer.BlockCopy() when you need to move data in and out of arrays. You don’t normally need to do this very heavily, but when you’re dealing with real-time multimedia, you’ll find yourself doing it all the time, so the faster you can do it, the better.

I mention this because a common way to move data from one array to another is through a for loop, like so:

   1:  for (int i = 0; i < sourceArray.Length; i++)
   2:  {
   3:      destinationArray[i] = sourceArray[i];
   4:  }

Unfortunately, that’s very nearly the slowest way to do it. (Array.Clone() is actually slower, but that’s another story.) A much better way to do it is to use Array.Copy(). Indeed, this is normally the preferred method, since you don’t have to worry about the size of the individual elements, which is an easy place to mess up. Moreover, Array.Copy() works for arrays of any type, instead of just intrinsic value types.

   1:  Array.Copy(sourceArray, 0, destinationArray, 0, sourceArray.Length);

But as it turns out, Buffer.BlockCopy() is slightly faster for many operations, since it doesn’t have to perform certain checks at the beginning of the copy:

   1:  Buffer.BlockCopy(sourceArray, 0, destinationArray, 0, sourceArray.Length * sizeof(short));

Benchmark results on my machine (10 million copies of a 64-element short[] array):

Buffer.BlockCopy action completed: iteration = 5, completionTime = 420, averageCompletionTime = 422.000
Array.Copy action completed: iteration = 5, completionTime = 478, averageCompletionTime = 482.600
forLoop action completed: iteration = 5, completionTime = 1092, averageCompletionTime = 1093.000

That said, the difference between Array.Copy() and Buffer.BlockCopy() tends to disappear the larger the amount of data to copy (while a for loop falls further and further behind). If you’re copying 64,000 elements instead of 64 elements, these are the results:

Buffer.BlockCopy action completed: iteration = 5, completionTime = 1251, averageCompletionTime = 1229.000
Array.Copy action completed: iteration = 5, completionTime = 1254, averageCompletionTime = 1218.200
forLoop action completed: iteration = 5, completionTime = 11063, averageCompletionTime = 11082.200

But there’s one significant caveat: if you only need to move a few elements, even the minimal overhead of Buffer.BlockCopy() can be too much. If you need to move less than 32 elements, you’ll probably find that a straightforward for loop (or perhaps an unrolled version of it) is the fastest. Of course, you’ll want to do your own testing to find out where the break-even point is. But here are my results with 1,000,000 copies of a 16-element array:

Buffer.BlockCopy action completed: iteration = 5, completionTime = 367, averageCompletionTime = 363.800
Array.Copy action completed: iteration = 5, completionTime = 418, averageCompletionTime = 420.000
forLoop action completed: iteration = 5, completionTime = 291, averageCompletionTime = 290.000

Tuesday, November 1, 2011

Fast (approximate) Sqrt method in C#

As part of the video codec that Alanta uses, we need to calculate the variation between blocks in one frame and the equivalent blocks in the next frame. I’ve been using an algorithm proposed by Thiadmer Riemersma that looks something like this:

public static double GetColorDistance(byte r1, byte g1, byte b1, byte r2, byte g2, byte b2)
{
    int rmean = (r1 + r2) / 2;
    int r = r1 - r2;
    int g = g1 - g2;
    int b = b1 - b2;
    int weightR = 2 + rmean / 256;
    const int weightG = 4;
    int weightB = 2 + (255 - rmean) / 256;
    return Math.Sqrt(weightR * r * r + weightG * g * g + weightB * b * b);
}

It works pretty well, but that last step depends on a square root calculation, which is relatively slow; and when this is something you need to run on every pixel in a frame, you want it to be as fast as possible. Consequently, I’ve been looking at ways to optimize it.

The important thing to note is that for my purposes, close is good enough: I don’t need IEEE precision. It turns out that there’s a pretty good approximation that’s available in languages like C or C++ which let you do unsafe casts back and forth between ints and floats:

float sqrt_approx(float z)
{
    union
    {
        int tmp;
        float f;
    } u;
    u.f = z;
    u.tmp -= 1 << 23; /* Subtract 2^m. */
    u.tmp >>= 1; /* Divide by 2. */
    u.tmp += 1 << 29; /* Add ((b + 1) / 2) * 2^m. */
    return u.f;
}
The problem with this approach is that C# doesn’t normally let you play this kind of magic.
The key word being “normally”, of course.
Turns out there’s one trick you can use to make C# treat the same memory address as either an int or a float, and that’s to create a struct with a [StructLayout(LayoutKind.Explicit)] attribute. (And surprisingly enough, the trick works in Silverlight as well.) The resulting class looks like this:
public class Approximate
{
    public static float Sqrt(float z)
    {
        if (z == 0) return 0;
        FloatIntUnion u;
        u.tmp = 0;
        u.f = z;
        u.tmp -= 1 << 23; /* Subtract 2^m. */
        u.tmp >>= 1; /* Divide by 2. */
        u.tmp += 1 << 29; /* Add ((b + 1) / 2) * 2^m. */
        return u.f;
    }

    [StructLayout(LayoutKind.Explicit)]
    private struct FloatIntUnion
    {
        [FieldOffset(0)]
        public float f;

        [FieldOffset(0)]
        public int tmp;
    }
}
The results are pretty good: it’s more than twice as fast, and the results tend to be within 2% of the “real” answer:

MathSqrtTest: averageCompletionTime = 2424.000
ApproxSqrtTest: averageCompletionTime = 1058.000
Average variation: 0.0253587081881525

If you want a bit more accuracy at the cost of an additional CPU cycle or two, you can use this one, based on the famous inverse square root method in Quake 3:

public static float Sqrt2(float z)
{
    if (z == 0) return 0;
    FloatIntUnion u;
    u.tmp = 0;
    float xhalf = 0.5f * z;
    u.f = z;
    u.tmp = 0x5f375a86 - (u.tmp >> 1);
    u.f = u.f * (1.5f - xhalf * u.f * u.f);
    return u.f * z;
}
It’s a tad slower than the first (though still nearly 2x as fast as Math.Sqrt()), but much more accurate:

MathSqrtTest: averageCompletionTime = 2428.400
ApproxSqrt2Test: averageCompletionTime = 1361.000
Average variation for method2: 0.000928551700594071