text:
When is assembly faster than C? [closed]
Closed. This question needs to be more focused. It is not currently accepting answers.
Closed 8 months ago.
One of the stated reasons for knowing assembler is that, on occasion, it can be employed to write code that will be more performant than writing that code in a higher-level language, C in particular. However, I've also heard it stated many times that although that's not entirely false, the cases where assembler can actually be used to generate more performant code are both extremely rare and require expert knowledge of and experience with assembly.
This question doesn't even get into the fact that assembler instructions will be machine-specific and non-portable, or any of the other aspects of assembler. There are plenty of good reasons for knowing assembly besides this one, of course, but this is meant to be a specific question soliciting examples and data, not an extended discourse on assembler versus higher-level languages.
Can anyone provide some specific examples of cases where assembly will be faster than well-written C code using a modern compiler, and can you support that claim with profiling evidence? I am pretty confident these cases exist, but I really want to know exactly how esoteric these cases are, since it seems to be a point of some contention.
c performance assembly
Adam Bellaire
actually it is quite trivial to improve upon compiled code. Anyone with a solid knowledge of assembly language and C can see this by examining the code generated. Any easy one is the first performance cliff you fall off of when you run out of disposable registers in the compiled version. On average the compiler will do far better than a human for a large project, but it is not hard in a decent sized project to find performance issues in the compiled code.
– old_timer
Actually, the short answer is: Assembler is always faster or equal to the speed of C. The reason is that you can have assembly without C, but you can't have C without assembly (in the binary form, which we in the old days called "machine code"). That said, the long answer is: C Compilers are pretty good at optimizing and "thinking" about things you don't usually think of, so it really depends on your skills, but normally you can always beat the C compiler; it's still only a software that can't think and get ideas. You can also write portable assembler if you use macros and you're patient.
I strongly disagree that answers to this question need to be "opinion based" - they can quite objective - it is not something like trying to compare performance of favorite pet languages, for which each will have strong points and draw backs. This is a matter of understanding how far compilers can take us, and from which point it is better to take over.
– jsbueno
Earlier in my career, I was writing a lot of C and mainframe assembler at a software company. One of my peers was what I'd call an "assembler purist" (everything had to be assembler), so I bet him I could write a given routine that ran faster in C than what he could write in assembler. I won. But to top it off, after I won, I told him I wanted a second bet - that I could write something faster in assembler than the C program that beat him on the prior wager. I won that too, proving that most of it comes down to the skill and ability of the programmer more than anythings else.
– Valerie R
@RobertF: We often leave off the "at what cost" part of these questions. I can write fast C or Assembler - sometimes the C is cheaper to write, and sometimes the assembler is cheaper to write. Speed often comes two ways: better algorithms or low-level infrastructure exploitation -quicksort in C will typically be faster than bubble sort in assembler. But if you implement identical logic in both, usually assembler gives you ways to exploit the machine architecture better than the compiler can - the compiler is general purpose, and you're creating a specific adaptation for a single use case.
Comments disabled on deleted / locked posts / reviews | Show 5 more comments
Here is a real world example: Fixed point multiplies on old compilers.
These don't only come handy on devices without floating point, they shine when it comes to precision as they give you 32 bits of precision with a predictable error (float only has 23 bit and it's harder to predict precision loss). i.e. uniform absolute precision over the entire range, instead of close-to-uniform relative precision (float).
Modern compilers optimize this fixed-point example nicely, so for more modern examples that still need compiler-specific code, see
Getting the high part of 64 bit integer multiplication: A portable version using uint64_t for 32x32 => 64-bit multiplies fails to optimize on a 64-bit CPU, so you need intrinsics or __int128 for efficient code on 64-bit systems.
_umul128 on Windows 32 bits: MSVC doesn't always do a good job when multiplying 32-bit integers cast to 64, so intrinsics helped a lot.
C doesn't have a full-multiplication operator (2N-bit result from N-bit inputs). The usual way to express it in C is to cast the inputs to the wider type and hope the compiler recognizes that the upper bits of the inputs aren't interesting:
// on a 32-bit machine, int can hold 32-bit fixed-point integers.
int inline FixedPointMul (int a, int b)
long long a_long = a; // cast to 64 bit.
long long product = a_long * b; // perform multiplication
return (int) (product >> 16);  // shift by the fixed point bias
The problem with this code is that we do something that can't be directly expressed in the C-language. We want to multiply two 32 bit numbers and get a 64 bit result of which we return the middle 32 bit. However, in C this multiply does not exist. All you can do is to promote the integers to 64 bit and do a 64*64 = 64 multiply.
x86 (and ARM, MIPS and others) can however do the multiply in a single instruction. Some compilers used to ignore this fact and generate code that calls a runtime library function to do the multiply. The shift by 16 is also often done by a library routine (also the x86 can do such shifts).
So we're left with one or two library calls just for a multiply. This has serious consequences. Not only is the shift slower, registers must be preserved across the function calls and it does not help inlining and code-unrolling either.
If you rewrite the same code in (inline) assembler you can gain a significant speed boost.
In addition to this: using ASM is not the best way to solve the problem. Most compilers allow you to use some assembler instructions in intrinsic form if you can't express them in C. The VS.NET2008 compiler for example exposes the 32*32=64 bit mul as __emul and the 64 bit shift as __ll_rshift.
Using intrinsics you can rewrite the function in a way that the C-compiler has a chance to understand what's going on. This allows the code to be inlined, register allocated, common subexpression elimination and constant propagation can be done as well. You'll get a huge performance improvement over the hand-written assembler code that way.
For reference: The end-result for the fixed-point mul for the VS.NET compiler is:
return (int) __ll_rshift(__emul(a,b),16);
The performance difference of fixed point divides is even bigger. I had improvements up to factor 10 for division heavy fixed point code by writing a couple of asm-lines.
Using Visual C++ 2013 gives the same assembly code for both ways.
gcc4.1 from 2007 also optimizes the pure C version nicely. (The Godbolt compiler explorer doesn't have any earlier versions of gcc installed, but presumably even older GCC versions could do this without intrinsics.)
See source + asm for x86 (32-bit) and ARM on the Godbolt compiler explorer. (Unfortunately it doesn't have any compilers old enough to produce bad code from the simple pure C version.)
Modern CPUs can do things C doesn't have operators for at all, like popcnt or bit-scan to find the first or last set bit. (POSIX has a ffs() function, but its semantics don't match x86 bsf / bsr. See https://en.wikipedia.org/wiki/Find_first_set).
Some compilers can sometimes recognize a loop that counts the number of set bits in an integer and compile it to a popcnt instruction (if enabled at compile time), but it's much more reliable to use __builtin_popcnt in GNU C, or on x86 if you're only targeting hardware with SSE4.2: _mm_popcnt_u32 from <immintrin.h>.
Or in C++, assign to a std::bitset<32> and use .count(). (This is a case where the language has found a way to portably expose an optimized implementation of popcount through the standard library, in a way that will always compile to something correct, and can take advantage of whatever the target supports.) See also https://en.wikipedia.org/wiki/Hamming_weight#Language_support.
Similarly, ntohl can compile to bswap (x86 32-bit byte swap for endian conversion) on some C implementations that have it.
Another major area for intrinsics or hand-written asm is manual vectorization with SIMD instructions. Compilers are not bad with simple loops like dst[i] += src[i] * 10.0;, but often do badly or don't auto-vectorize at all when things get more complicated. For example, you're unlikely to get anything like How to implement atoi using SIMD? generated automatically by the compiler from scalar code.
Nils Pipenbrinck
How about things like {x=c%d; y=c/d;}, are compilers clever enough to make that a single div or idiv?
– Jens Björnhager
Actually, a good compiler would produce the optimal code from the first function. Obscuring the source code with intrinsics or inline assembly with absolutely no benefit is not the best thing to do.
– slacker
Hi Slacker, I think you've never had to work on time-critical code before... inline assembly can make a *huge difference. Also for the compiler an intrinsic is the same as normal arithmetic in C. That's the point in intrinsics. They let you use a architecture feature without having to deal with the drawbacks.
– Nils Pipenbrinck
@slacker Actually, the code here is quite readable: the inline code does one unique operation, which is immediately understable reading the method signature. The code lost only slowly in readibility when an obscure instruction is used. What matters here is we have a method which does only one clearly identifiable operation, and that's really the best way to produce readable code these atomic functions. By the way, this is not so obscure a small comment like /* (a * b) >> 16 */ can't immediately explain it.
– Dereckson
To be fair, this is example is a poor one, at least today. C compilers have long been able to do a 32x32 -> 64 multiply even if the language doesn't offer it directly: they recognize that when you cast 32-bit arguments to 64-bit and then multiply them, it doesn't need to do a full 64-bit multiply, but that a 32x32 -> 64 will do just fine. I checked and all of clang, gcc and MSVC in their current version get this right. This isn't new - I remember looking at compiler output and noticing this a decade a ago.
– BeeOnRope
Many years ago I was teaching someone to program in C. The exercise was to rotate a graphic through 90 degrees. He came back with a solution that took several minutes to complete, mainly because he was using multiplies and divides etc.
I showed him how to recast the problem using bit shifts, and the time to process came down to about 30 seconds on the non-optimizing compiler he had.
I had just got an optimizing compiler and the same code rotated the graphic in < 5 seconds. I looked at the assembly code that the compiler was generating, and from what I saw decided there and then that my days of writing assembler were over.
Peter Cordes
Just wondering: Was the graphic in 1 bit per pixel format?
Yes it was a one bit monochrome system, specifically it was the monochrome image blocks on an Atari ST.
– lilburne
Did the optimizing compiler compile the original program or your version?
– Thorbjørn Ravn Andersen
On what processor? On 8086, I'd expect that optimal code for an 8x8 rotate would load DI with 16 bits of data using SI, repeat add di,di / adc al,al / add di,di / adc ah,ah etc. for all eight 8-bit registers, then do all 8 registers again, and then repeat the whole procedure three more times, and finally save four words in ax/bx/cx/dx. No way an assembler is going to come close to that.
– supercat
I really can't think of any platform where a compiler would be likely to get within a factor or two of optimal code for an 8x8 rotate.
Pretty much anytime the compiler sees floating point code, a hand written version will be quicker if you're using an old bad compiler. (2019 update: This is not true in general for modern compilers. Especially when compiling for anything other than x87; compilers have an easier time with SSE2 or AVX for scalar math, or any non-x86 with a flat FP register set, unlike x87's register stack.)
The primary reason is that the compiler can't perform any robust optimisations. See this article from MSDN for a discussion on the subject. Here's an example where the assembly version is twice the speed as the C version (compiled with VS2K5):
float KahanSum(const float *data, int n)
float sum = 0.0f, C = 0.0f, Y, T;
for (int i = 0 ; i < n ; ++i) {
Y = *data++ - C;
T = sum + Y;
C = T - sum - Y;
sum = T;
float AsmSum(const float *data, int n)
float result = 0.0f;
_asm
mov esi,data
mov ecx,n
fldz
l1:
fsubr [esi]
add esi,4
fld st(0)
fadd st(0),st(2)
fsub st(0),st(3)
fstp st(2)
loop l1
fstp result
int main (int, char **)
int count = 1000000;
float *source = new float [count];
for (int i = 0 ; i < count ; ++i) {
source [i] = static_cast <float> (rand ()) / static_cast <float> (RAND_MAX);
LARGE_INTEGER start, mid, end;
float sum1 = 0.0f, sum2 = 0.0f;
QueryPerformanceCounter (&start);
sum1 = KahanSum (source, count);
QueryPerformanceCounter (&mid);
sum2 = AsmSum (source, count);
QueryPerformanceCounter (&end);
cout << "  C code: " << sum1 << " in " << (mid.QuadPart - start.QuadPart) << endl;
cout << "asm code: " << sum2 << " in " << (end.QuadPart - mid.QuadPart) << endl;
And some numbers from my PC running a default release build*:
C code: 500137 in 103884668
asm code: 500137 in 52129147
Out of interest, I swapped the loop with a dec/jnz and it made no difference to the timings - sometimes quicker, sometimes slower. I guess the memory limited aspect dwarfs other optimisations. (Editor's note: more likely the FP latency bottleneck is enough to hide the extra cost of loop. Doing two Kahan summations in parallel for the odd/even elements, and adding those at the end, could maybe speed this up by a factor of 2.)
Whoops, I was running a slightly different version of the code and it outputted the numbers the wrong way round (i.e. C was faster!). Fixed and updated the results.
Skizz
Or in GCC, you can untie the compiler's hands on floating point optimization (as long as you promise not to do anything with infinities or NaNs) by using the flag -ffast-math. They have an optimization level, -Ofast that is currently equivalent to -O3 -ffast-math, but in the future may include more optimizations that can lead to incorrect code generation in corner cases (such as code that relies on IEEE NaNs).
– David Stone
Yeah, floats are not commutative, the compiler must do EXACTLY what you wrote, basically what @DavidStone said.
– Alec Teal
Did you try SSE math? Performance was one of the reasons MS abandoned x87 completely in x86_64 and 80-bit long double in x86
– phuclv
@Praxeolitic: FP add is commutative (a+b == b+a), but not associative (reordering of operations, so rounding of intermediates is different). re: this code: I don't think uncommented x87 and a loop instruction are a very awesome demonstration of fast asm. loop is apparently not actually a bottleneck because of FP latency. I'm not sure if he's pipelining FP operations or not; x87 is hard for humans to read. Two fstp results insns at the end is clearly not optimal. Popping the extra result from the stack would be better done with a non-store. Like fstp st(0) IIRC.
– Peter Cordes
@PeterCordes: An interesting consequence of making addition commutative is that while 0+x and x+0 are equivalent to each other, neither is always equivalent to x.
Without giving any specific example or profiler evidence, you can write better assembler than the compiler when you know more than the compiler.
In the general case, a modern C compiler knows much more about how to optimize the code in question: it knows how the processor pipeline works, it can try to reorder instructions quicker than a human can, and so on - it's basically the same as a computer being as good as or better than the best human player for boardgames, etc. simply because it can make searches within the problem space faster than most humans. Although you theoretically can perform as well as the computer in a specific case, you certainly can't do it at the same speed, making it infeasible for more than a few cases (i.e. the compiler will most certainly outperform you if you try to write more than a few routines in assembler).
On the other hand, there are cases where the compiler does not have as much information - I'd say primarily when working with different forms of external hardware, of which the compiler has no knowledge. The primary example probably being device drivers, where assembler combined with a human's intimate knowledge of the hardware in question can yield better results than a C compiler could do.
Others have mentioned special purpose instructions, which is what I'm talking in the paragraph above - instructions of which the compiler might have limited or no knowledge at all, making it possible for a human to write faster code.
Liedman
Generally, this statement is true. The compiler does it's best to DWIW, but in some edge cases hand coding assembler gets the job done when realtime performance is a must.
– spoulson
@Liedman: "it can try to reorder instructions quicker than a human can". OCaml is known for being fast and, surprisingly, its native-code compiler ocamlopt skips instruction scheduling on x86 and, instead, leaves it up to the CPU because it can reorder more effectively at run-time.
Modern compilers do a lot, and it would take way too long to do by hand, but they're nowhere near perfect. Search gcc or llvm's bug trackers for "missed-optimization" bugs. There are many. Also, when writing in asm, you can more easily take advantage of preconditions like "this input can't be negative" that would be hard for a compiler to prove.
In my job, there are three reasons for me to know and use assembly. In order of importance:
Debugging - I often get library code that has bugs or incomplete documentation. I figure out what it's doing by stepping in at the assembly level. I have to do this about once a week. I also use it as a tool to debug problems in which my eyes don't spot the idiomatic error in C/C++/C#. Looking at the assembly gets past that.
Optimizing - the compiler does fairly well in optimizing, but I play in a different ballpark than most. I write image processing code that usually starts with code that looks like this:
for (int y=0; y < imageHeight; y++) {
for (int x=0; x < imageWidth; x++) {
the "do something part" typically happens on the order of several million times (ie, between 3 and 30). By scraping cycles in that "do something" phase, the performance gains are hugely magnified. I don't usually start there - I usually start by writing the code to work first, then do my best to refactor the C to be naturally better (better algorithm, less load in the loop etc). I usually need to read assembly to see what's going on and rarely need to write it. I do this maybe every two or three months.
doing something the language won't let me. These include - getting the processor architecture and specific processor features, accessing flags not in the CPU (man, I really wish C gave you access to the carry flag), etc. I do this maybe once a year or two years.
@plinth: how do you mean "scraping cycles"?
– lang2
@lang2: it means getting rid of as many superfluous time spent in the inner loop as possible - anything that the compiler didn't manage to pull out, which may include using algebra to lift a multiply out of one loop to make it an add in the inner, etc.
– plinth
Loop tiling appears to be unnecessary if you are only making one pass over the data.
– James M. Lay
@JamesM.Lay: If you you only touch every element once, a better traversal order can give you spatial locality. (e.g. use all the bytes of a cache line that you touched, instead of looping down columns of a matrix using one element per cache line.)
Only when using some special purpose instruction sets the compiler doesn't support.
To maximize the computing power of a modern CPU with multiple pipelines and predictive branching you need to structure the assembly program in a way that makes it a) almost impossible for a human to write b) even more impossible to maintain.
Also, better algorithms, data structures and memory management will give you at least an order of magnitude more performance than the micro-optimizations you can do in assembly.
+1, even though the last sentence doesn't really belong into this discussion - one would assume that assembler comes into play only after all possible improvements of algorithm etc have been realized.
– mghie
@Matt: Hand written ASM is often a lot better on some of the tiny CPUs EE's work with that have crappy vendor compiler support.
– Zan Lynx
"Only when using some special purpose instruction sets"?? You probably have never written a piece of hand-optimized asm code before. A moderately intimate knowledge of the architecture you are working on gives a good chance for you to generate a better code (size and speed) than your compiler. Obviously, as @mghie commented, you always start coding the best algos you can come with for you problem. Even for very good compilers, you really have to write your C code in a way that leads the compiler to the best compiled code. Otherwise, the generated code will be sub-optimal.
– ysap
@ysap - on actual computers (not tiny underpowered embedded chips) in real world usage, the "optimal" code isn't going to be faster because for any large data set you performance is going to be limited by memory access and page faults (and if you don't have a large data set this is going to be fast either way and there's no point optimizing it) - those days I work mostly in C# (not even c) and the performance gains from the compacting memory manager out-weight the overhead of the garbage collection, compacting and and JIT compilation.
– Nir
+1 for stating that compilers (esp. JIT) can do a better job than humans, if they are optimized for the hardware they are run on.
– Sebastian
Although C is "close" to the low-level manipulation of 8-bit, 16-bit, 32-bit, 64-bit data, there are a few mathematical operations not supported by C which can often be performed elegantly in certain assembly instruction sets:
Fixed-point multiplication: The product of two 16-bit numbers is a 32-bit number. But the rules in C says that the product of two 16-bit numbers is a 16-bit number, and the product of two 32-bit numbers is a 32-bit number -- the bottom half in both cases. If you want the top half of a 16x16 multiply or a 32x32 multiply, you have to play games with the compiler. The general method is to cast to a larger-than-necessary bit width, multiply, shift down, and cast back:
int16_t x, y;
// int16_t is a typedef for "short"
// set x and y to something
int16_t prod = (int16_t)(((int32_t)x*y)>>16);`
In this case the compiler may be smart enough to know that you're really just trying to get the top half of a 16x16 multiply and do the right thing with the machine's native 16x16multiply. Or it may be stupid and require a library call to do the 32x32 multiply that's way overkill because you only need 16 bits of the product -- but the C standard doesn't give you any way to express yourself.
Certain bitshifting operations (rotation/carries):
// 256-bit array shifted right in its entirety:
uint8_t x[32];
for (int i = 32; --i > 0; )
x[i] = (x[i] >> 1) | (x[i-1] << 7);
x[0] >>= 1;
This is not too inelegant in C, but again, unless the compiler is smart enough to realize what you are doing, it's going to do a lot of "unnecessary" work. Many assembly instruction sets allow you to rotate or shift left/right with the result in the carry register, so you could accomplish the above in 34 instructions: load a pointer to the beginning of the array, clear the carry, and perform 32 8-bit right-shifts, using auto-increment on the pointer.
For another example, there are linear feedback shift registers (LFSR) that are elegantly performed in assembly: Take a chunk of N bits (8, 16, 32, 64, 128, etc), shift the whole thing right by 1 (see above algorithm), then if the resulting carry is 1 then you XOR in a bit pattern that represents the polynomial.
Having said that, I wouldn't resort to these techniques unless I had serious performance constraints. As others have said, assembly is much harder to document/debug/test/maintain than C code: the performance gain comes with some serious costs.
edit: 3. Overflow detection is possible in assembly (can't really do it in C), this makes some algorithms much easier.
Jason S
Short answer? Sometimes.
Technically every abstraction has a cost and a programming language is an abstraction for how the CPU works. C however is very close. Years ago I remember laughing out loud when I logged onto my UNIX account and got the following fortune message (when such things were popular):
The C Programming Language -- A language which combines the flexibility of assembly language with the power of assembly language.
It's funny because it's true: C is like portable assembly language.
It's worth noting that assembly language just runs however you write it. There is however a compiler in between C and the assembly language it generates and that is extremely important because how fast your C code is has an awful lot to do with how good your compiler is.
When gcc came on the scene one of the things that made it so popular was that it was often so much better than the C compilers that shipped with many commercial UNIX flavours. Not only was it ANSI C (none of this K&R C rubbish), was more robust and typically produced better (faster) code. Not always but often.
I tell you all this because there is no blanket rule about the speed of C and assembler because there is no objective standard for C.
Likewise, assembler varies a lot depending on what processor you're running, your system spec, what instruction set you're using and so on. Historically there have been two CPU architecture families: CISC and RISC. The biggest player in CISC was and still is the Intel x86 architecture (and instruction set). RISC dominated the UNIX world (MIPS6000, Alpha, Sparc and so on). CISC won the battle for the hearts and minds.
Anyway, the popular wisdom when I was a younger developer was that hand-written x86 could often be much faster than C because the way the architecture worked, it had a complexity that benefitted from a human doing it. RISC on the other hand seemed designed for compilers so noone (I knew) wrote say Sparc assembler. I'm sure such people existed but no doubt they've both gone insane and been institutionalized by now.
Instruction sets are an important point even in the same family of processors. Certain Intel processors have extensions like SSE through SSE4. AMD had their own SIMD instructions. The benefit of a programming language like C was someone could write their library so it was optimized for whichever processor you were running on. That was hard work in assembler.
There are still optimizations you can make in assembler that no compiler could make and a well written assembler algoirthm will be as fast or faster than it's C equivalent. The bigger question is: is it worth it?
Ultimately though assembler was a product of its time and was more popular at a time when CPU cycles were expensive. Nowadays a CPU that costs $5-10 to manufacture (Intel Atom) can do pretty much anything anyone could want. The only real reason to write assembler these days is for low level things like some parts of an operating system (even so the vast majority of the Linux kernel is written in C), device drivers, possibly embedded devices (although C tends to dominate there too) and so on. Or just for kicks (which is somewhat masochistic).
There were a many people who used ARM assembler as the language of choice on Acorn machines (early 90's). IIRC they said that the small risc instruction set made it easier and more fun. But I suspect it's because the C compiler was a late arrival for Acorn, and the C++ compiler was never finished.
– Andrew M
@AndrewM: Yeah, I wrote mixed-language applications in BASIC and ARM assembler for about 10 years. I learned C during that time but it wasn't very useful because it is as cumbersome as assembler and slower. Norcroft did some awesome optimizations but I think the conditional instruction set was a problem for the compilers of the day.
@AndrewM: well, actually ARM is kind of RISC done backwards. Other RISC ISAs were designed starting with what a compiler would use. The ARM ISA seems to have been designed starting with what the CPU provides (barrel shifter, condition flags → let's expose them in every instruction).
– ninjalj
I'm surprised no one said this. The strlen() function is much faster if written in assembly! In C, the best thing you can do is
int c;
for(c = 0; str[c] != '\0'; c++) {}
while in assembly you can speed it up considerably:
mov esi, offset string
mov edi, esi
xor ecx, ecx
mov ax, byte ptr [esi]
cmp al, cl
je  end_1
cmp ah, cl
je end_2
mov bx, byte ptr [esi + 2]
cmp bl, cl
cmp bh, cl
add esi, 4
jmp lp
end_4:
inc esi
mov ecx, esi
sub ecx, edi
the length is in ecx. This compares 4 characters at time, so it's 4 times faster. And think using the high order word of eax and ebx, it will become 8 times faster that the previous C routine!
How does this compare with the ones in strchr.nfshost.com/optimized_strlen_function ?
@ninjalj: they are the same thing :) i didn't thought it can be done this way in C. It can be slightly improved I think
– BlackBear
There's still a bitwise AND operation before each comparison in the C code. It's possible that the compiler would be smart enough to reduce that to high and low byte comparisons, but I wouldn't bet money on it. There's actually a faster loop algorithm that's based on the property that (word & 0xFEFEFEFF) & (~word + 0x80808080) is zero iff all bytes in word are non-zero.
A use case which might not apply anymore but for your nerd pleasure: On the Amiga, the CPU and the graphics/audio chips would fight for accessing a certain area of RAM (the first 2MB of RAM to be specific). So when you had only 2MB RAM (or less), displaying complex graphics plus playing sound would kill the performance of the CPU.
In assembler, you could interleave your code in such a clever way that the CPU would only try to access the RAM when the graphics/audio chips were busy internally (i.e. when the bus was free). So by reordering your instructions, clever use of the CPU cache, the bus timing, you could achieve some effects which were simply not possible using any higher level language because you had to time every command, even insert NOPs here and there to keep the various chips out of each others radar.
Which is another reason why the NOP (No Operation - do nothing) instruction of the CPU can actually make your whole application run faster.
[EDIT] Of course, the technique depends on a specific hardware setup. Which was the main reason why many Amiga games couldn't cope with faster CPUs: The timing of the instructions was off.
Aaron Digulla
The Amiga didn't have 16 MB of chip RAM, more like 512 kB to 2 MB depending on chipset. Also, a lot of Amiga games didn't work with faster CPUs due to techniques like you describe.
– bk1e
@bk1e - Amiga produced a large range of different models of computers, the Amiga 500 shipped with 512K ram extended to 1Meg in my case. amigahistory.co.uk/amiedevsys.html is an amiga with 128Meg Ram
– David Waters
@bk1e: I stand corrected. My memory may fail me but wasn't chip RAM restricted to the first 24bit address space (i.e. 16MB)? And Fast was mapped above that?
– Aaron Digulla
@Aaron Digulla: Wikipedia has more info about the distinctions between chip/fast/slow RAM: en.wikipedia.org/wiki/Amiga_Chip_RAM
@bk1e: My mistake. The 68k CPU had only 24 address lanes, that's why I had the 16MB in my head.
Point one which is not the answer.
Even if you never program in it, I find it useful to know at least one assembler instruction set. This is part of the programmers never-ending quest to know more and therefore be better. Also useful when stepping into frameworks you don't have the source code to and having at least a rough idea what is going on. It also helps you to understand JavaByteCode and .Net IL as they are both similar to assembler.
To answer the question when you have a small amount of code or a large amount of time. Most useful for use in embedded chips, where low chip complexity and poor competition in compilers targeting these chips can tip the balance in favour of humans. Also for restricted devices you are often trading off code size/memory size/performance in a way that would be hard to instruct a compiler to do. e.g. I know this user action is not called often so I will have small code size and poor performance, but this other function that look similar is used every second so I will have a larger code size and faster performance. That is the sort of trade off a skilled assembly programmer can use.
I would also like to add there is a lot of middle ground where you can code in C compile and examine the Assembly produced, then either change you C code or tweak and maintain as assembly.
My friend works on micro controllers, currently chips for controlling small electric motors. He works in a combination of low level c and Assembly. He once told me of a good day at work where he reduced the main loop from 48 instructions to 43. He is also faced with choices like the code has grown to fill the 256k chip and the business is wanting a new feature, do you
Remove an existing feature
Reduce the size of some or all of the existing features maybe at the cost of performance.
Advocate moving to a larger chip with a higher cost, higher power consumption and larger form factor.
I would like to add as a commercial developer with quite a portfolio or languages, platforms, types of applications I have never once felt the need to dive into writing assembly. I have how ever always appreciated the knowledge I gained about it. And sometimes debugged into it.
I know I have far more answered the question "why should I learn assembler" but I feel it is a more important question then when is it faster.
so lets try once more You should be thinking about assembly
working on low level operating system function
Working on a compiler.
Working on an extremely limited chip, embedded system etc
Remember to compare your assembly to compiler generated to see which is faster/smaller/better.
David Waters
+1 for considering embedded applications on tiny chips. Too many software engineers here either don't consider embedded or think that means a smart phone (32 bit, MB RAM, MB flash).
– Martin
Time embedded applications are a great example! There are often weird instructions (even really simple ones like avr's sbi and cbi) that compilers used to (and sometimes still do) not take full advantage of, due to their limited knowledge of the hardware.
– felixphew
You write "This is part of the programmers never-ending quest to know more and therefore be better" bit i beg to differ. I would express it as "This is part of some programmers' never-ending quest to know more and therefore be better". Most couldn't care less.
– Olof Forshell
Matrix operations using SIMD instructions is probably faster than compiler generated code.
Some compilers (the VectorC, if I remember correctly) generate SIMD code, so even that is probably no longer an argument for using assembly code.
– OregonGhost
For many of those situations you can use SSE intrisics instead of assembly. This will make your code more portable (gcc visual c++, 64bit, 32bit etc) and you don't have to do register allocation.
– Laserallan
Sure you would, but the question did not ask where should I use assembly instead of C. It said when C compiler doesn't generate a better code. I assumed a C source that is not using direct SSE calls or inline assembly.
– mmx
Mehrdad is right, though. Getting SSE right is quite hard for the compiler and even in obvious (for humans, that is) situations most compilers don't employ it.
– Konrad Rudolph
You should use intrinsics for that, so it's not really assembler..
– Nils
A few examples from my experience:
Access to instructions that are not accessible from C. For instance, many architectures (like x86-64, IA-64, DEC Alpha, and 64-bit MIPS or PowerPC) support a 64 bit by 64 bit multiplication producing a 128 bit result. GCC recently added an extension providing access to such instructions, but before that assembly was required. And access to this instruction can make a huge difference on 64-bit CPUs when implementing something like RSA - sometimes as much as a factor of 4 improvement in performance.
Access to CPU-specific flags. The one that has bitten me a lot is the carry flag; when doing a multiple-precision addition, if you don't have access to the CPU carry bit one must instead compare the result to see if it overflowed, which takes 3-5 more instructions per limb; and worse, which are quite serial in terms of data accesses, which kills performance on modern superscalar processors. When processing thousands of such integers in a row, being able to use addc is a huge win (there are superscalar issues with contention on the carry bit as well, but modern CPUs deal pretty well with it).
SIMD. Even autovectorizing compilers can only do relatively simple cases, so if you want good SIMD performance it's unfortunately often necessary to write the code directly. Of course you can use intrinsics instead of assembly but once you're at the intrinsics level you're basically writing assembly anyway, just using the compiler as a register allocator and (nominally) instruction scheduler. (I tend to use intrinsics for SIMD simply because the compiler can generate the function prologues and whatnot for me so I can use the same code on Linux, OS X, and Windows without having to deal with ABI issues like function calling conventions, but other than that the SSE intrinsics really aren't very nice - the Altivec ones seem better though I don't have much experience with them). As examples of things a (current day) vectorizing compiler can't figure out, read about bitslicing AES or SIMD error correction - one could imagine a compiler that could analyze algorithms and generate such code, but it feels to me like such a smart compiler is at least 30 years away from existing (at best).
On the other hand, multicore machines and distributed systems have shifted many of the biggest performance wins in the other direction - get an extra 20% speedup writing your inner loops in assembly, or 300% by running them across multiple cores, or 10000% by running them across a cluster of machines. And of course high level optimizations (things like futures, memoization, etc) are often much easier to do in a higher level language like ML or Scala than C or asm, and often can provide a much bigger performance win. So, as always, there are tradeoffs to be made.
Also, intrinsic based SIMD code tends to be less readable than the same code written in assembler: Much SIMD code relies on implicit reinterpretations of the data in the vectors, which is a PITA to do with the data types compiler intrinsics provide.
– cmaster - reinstate monica
I can't give the specific examples because it was too many years ago, but there were plenty of cases where hand-written assembler could out-perform any compiler. Reasons why:
You could deviate from calling conventions, passing arguments in registers.
You could carefully consider how to use registers, and avoid storing variables in memory.
For things like jump tables, you could avoid having to bounds-check the index.
Basically, compilers do a pretty good job of optimizing, and that is nearly always "good enough", but in some situations (like graphics rendering) where you're paying dearly for every single cycle, you can take shortcuts because you know the code, where a compiler could not because it has to be on the safe side.
In fact, I have heard of some graphics rendering code where a routine, like a line-draw or polygon-fill routine, actually generated a small block of machine code on the stack and executed it there, so as to avoid continual decision-making about line style, width, pattern, etc.
That said, what I want a compiler to do is generate good assembly code for me but not be too clever, and they mostly do that. In fact, one of the things I hate about Fortran is its scrambling the code in an attempt to "optimize" it, usually to no significant purpose.
Usually, when apps have performance problems, it is due to wasteful design. These days, I would never recommend assembler for performance unless the overall app had already been tuned within an inch of its life, still was not fast enough, and was spending all its time in tight inner loops.
Added: I've seen plenty of apps written in assembly language, and the main speed advantage over a language like C, Pascal, Fortran, etc. was because the programmer was far more careful when coding in assembler. He or she is going to write roughly 100 lines of code a day, regardless of language, and in a compiler language that's going to equal 3 or 400 instructions.
Mike Dunlavey
+1: "You could deviate from calling conventions". C/C++ compilers tend to suck at returning multiple values. They often use sret form where the caller stack allocates a contiguous block for a struct and passed a reference to it for the callee to fill it in. Returning multiple values in registers is several times faster.
@Jon: C/C++ compilers do that just fine when the function gets inlined (non-inlined functions have to conform to the ABI, this isn't a limitation of C and C++ but the linking model)
– Ben Voigt
@BenVoigt: Here's a counter example flyingfrogblog.blogspot.co.uk/2012/04/…
I don't see any function call getting inlined there.
More often than you think, C needs to do things that seem to be unneccessary from an Assembly coder's point of view just because the C standards say so.
Integer promotion, for example. If you want to shift a char variable in C, one would usually expect that the code would do in fact just that, a single bit shift.
The standards, however, enforce the compiler to do a sign extend to int before the shift and truncate the result to char afterwards which might complicate code depending on the target processor's architecture.
mfro
Quality compilers for small micros have for years been able to avoid processing the upper portions of values in cases where doing so could never meaningfully affect results. Promotion rules do cause problems, but most often in cases where a compiler has no way of knowing which corner cases are and are not relevant.
You don't actually know whether your well-written C code is really fast if you haven't looked at the disassembly of what compiler produces. Many times you look at it and see that "well-written" was subjective.
So it's not necessary to write in assembler to get fastest code ever, but it's certainly worth to know assembler for the very same reason.
sharptooth
"So it's not necessary to write in assembler to get fastest code ever" Well, I've not seen a compiler do the optimal thing in any case that was not trivial. An experienced human can do better than the compiler in virtually all cases. So, it's absolutely necessary to write in assembler to get "the fastest code ever".
@cmaster In my experience compiler output is well, random. Sometimes it's really good and optimal and sometimes is "how could this garbage have been emitted".
– sharptooth
Tight loops, like when playing with images, since an image may cosist of millions of pixels. Sitting down and figuring out how to make best use of the limited number of processor registers can make a difference. Here's a real life sample:
http://danbystrom.se/2008/12/22/optimizing-away-ii/
Then often processors have some esoteric instructions which are too specialized for a compiler to bother with, but on occasion an assembler programmer can make good use of them. Take the XLAT instruction for example. Really great if you need to do table look-ups in a loop and the table is limited to 256 bytes!
Updated: Oh, just come to think of what's most crucial when we speak of loops in general: the compiler has often no clue on how many iterations that will be the common case! Only the programmer know that a loop will be iterated MANY times and that it therefore will be beneficial to prepare for the loop with some extra work, or if it will be iterated so few times that the set-up actually will take longer than the iterations expected.
Dan Byström
Profile directed optimization gives the compiler information about how often a loop is used.
I have read all the answers (more than 30) and didn't find a simple reason: assembler is faster than C if you have read and practiced the Intel® 64 and IA-32 Architectures Optimization Reference Manual, so the reason why assembly may be slower is that people who write such slower assembly didn't read the Optimization Manual.
In the good old days of Intel 80286, each instruction was executed at a fixed count of CPU cycles. Still, since Pentium Pro, released in 1995, Intel processors became superscalar, utilizing Complex Pipelining: Out-of-Order Execution & Register Renaming. Before that, on Pentium, produced in 1993, there were U and V pipelines. Therefore, Pentium introduced dual pipelines that could execute two simple instructions at one clock cycle if they didn't depend on one another. However, this was nothing compared with the Out-of-Order Execution & Register Renaming that appeared in Pentium Pro. This approach introduced in Pentium Pro is practically the same nowadays on most recent Intel processors.
Let me explain the Out-of-Order Execution in a few words. The fastest code is where instructions do not depend on previous results, e.g., you should always clear whole registers (by movzx) to remove dependency from previous values of the registers you are working with, so they may be renamed internally by the CPU to allow instruction execute in parallel or in a different order. Or, on some processors, false dependency may exist that may also slow things down, like false dependency on Pentium 4 for inc/dec, so you may wish to use add eax, 1 instead or inc eax to remove dependency on the previous state of the flags.
You can read more on Out-of-Order Execution & Register Renaming if time permits. There is plenty of information available on the Internet.
There are also many other essential issues like branch prediction, number of load and store units, number of gates that execute micro-ops, memory cache coherence protocols, etc., but the crucial thing to consider is the Out-of-Order Execution. Most people are simply not aware of the Out-of-Order Execution. Therefore, they write their assembly programs like for 80286, expecting their instructions will take a fixed time to execute regardless of the context. At the same time, C compilers are aware of the Out-of-Order Execution and generate the code correctly. That's why the code of such uninformed people is slower, but if you become knowledgeable, your code will be faster.
There are also lots of optimization tips and tricks besides the Out-of-Order Execution. Just read the Optimization Manual above mentioned :-)
However, assembly language has its own drawbacks when it comes to optimization. According to Peter Cordes (see the comment below), some of the optimizations compilers do would be unmaintainable for large code-bases in hand-written assembly. For example, suppose you write in assembly. In that case, you need to completely change an inline function (an assembly macro) when it inlines into a function that calls it with some arguments being constants. At the same time, a C compiler makes its job a lot simpler—and inlining the same code in different ways into different call sites. There is a limit to what you can do with assembly macros. So to get the same benefit, you'd have to manually optimize the same logic in each place to match the constants and available registers you have.
Maxim Masiutin
It's also worth pointing out that some of the optimizations compilers do would be unmaintainable for large code-bases in hand-written asm. e.g. completely changing an inline function (asm macro) when it inlines into a function that calls it with some args being constants that makes its job a lot simpler. And inlining the same code different ways into different callsites. There's a limit to what you can do with asm macros. So to get the same benefit, you'd have to manually optimize the same logic in each place to match the constants and free registers you have.
I think the general case when assembler is faster is when a smart assembly programmer looks at the compiler's output and says "this is a critical path for performance and I can write this to be more efficient" and then that person tweaks that assembler or rewrites it from scratch.
Doug T.
It all depends on your workload.
For day-to-day operations, C and C++ are just fine, but there are certain workloads (any transforms involving video (compression, decompression, image effects, etc)) that pretty much require assembly to be performant.
They also usually involve using CPU specific chipset extensions (MME/MMX/SSE/whatever) that are tuned for those kinds of operation.
ReinstateMonica Larry Osterman
It might be worth looking at Optimizing Immutable and Purity by Walter Bright it's not a profiled test but shows you one good example of a difference between handwritten and compiler generated ASM. Walter Bright writes optimising compilers so it might be worth looking at his other blog posts.
James Brooks
LInux assembly howto, asks this question and gives the pros and cons of using assembly.
pseudosaint
I have an operation of transposition of bits that needs to be done, on 192 or 256 bits every interrupt, that happens every 50 microseconds.
It happens by a fixed map(hardware constraints). Using C, it took around 10 microseconds to make. When I translated this to Assembler, taking into account the specific features of this map, specific register caching, and using bit oriented operations; it took less than 3.5 microsecond to perform.
SurDin
The simple answer... One who knows assembly well (aka has the reference beside him, and is taking advantage of every little processor cache and pipeline feature etc) is guaranteed to be capable of producing much faster code than any compiler.
However the difference these days just doesn't matter in the typical application.
Longpoke
You forgot to say "given a lot of time and effort", and "creating a maintenance nightmare". A colleague of mine was working on optimising a performance-critical section of OS code, and he worked in C much more than assembly, as it let him investigate the performance impact of high-level changes within a reasonable timeframe.
– Artelius
I agree. Sometimes you use macros and scripts to generate assembly code in order to save time and develop rapidly. Most assemblers these days have macros; if not, you can make a (simple) macro pre-processor using a (fairly simple RegEx) Perl script.
This. Precisely. The compiler to beat the domain experts has not been invented yet.
http://cr.yp.to/qhasm.html has many examples.
One of the posibilities to the CP/M-86 version of PolyPascal (sibling to Turbo Pascal) was to replace the "use-bios-to-output-characters-to-the-screen" facility with a machine language routine which in essense was given the x, and y, and the string to put there.
This allowed to update the screen much, much faster than before!
There was room in the binary to embed machine code (a few hundred bytes) and there was other stuff there too, so it was essential to squeeze as much as possible.
It turnes out that since the screen was 80x25 both coordinates could fit in a byte each, so both could fit in a two-byte word. This allowed to do the calculations needed in fewer bytes since a single add could manipulate both values simultaneously.
To my knowledge there is no C compilers which can merge multiple values in a register, do SIMD instructions on them and split them out again later (and I don't think the machine instructions will be shorter anyway).
Thorbjørn Ravn Andersen
One of the more famous snippets of assembly is from Michael Abrash's texture mapping loop (expained in detail here):
add edx,[DeltaVFrac] ; add in dVFrac
sbb ebp,ebp ; store carry
mov [edi],al ; write pixel n
mov al,[esi] ; fetch pixel n+1
add ecx,ebx ; add in dUFrac
adc esi,[4*ebp + UVStepVCarry]; add in steps
Nowadays most compilers express advanced CPU specific instructions as intrinsics, i.e., functions that get compiled down to the actual instruction. MS Visual C++ supports intrinsics for MMX, SSE, SSE2, SSE3, and SSE4, so you have to worry less about dropping down to assembly to take advantage of platform specific instructions. Visual C++ can also take advantage of the actual architecture you are targetting with the appropriate /ARCH setting.
Even better, those SSE intrinsics are specified by Intel so they're actually fairly portable.
Given the right programmer, Assembler programs can always be made faster than their C counterparts (at least marginally). It would be difficult to create a C program where you couldn't take out at least one instruction of the Assembler.
Beep beep
This would be a bit more correct: "It would be difficult to create a nontrivial C program where ..." Alternatively, you could say: "It would be difficult to find a real-world C program where ..." Point is, there are trivial loops for which compilers do produce optimal output. Nevertheless, good answer.
gcc has become a widely used compiler. Its optimizations in general are not that good. Far better than the average programmer writing assembler, but for real performance, not that good. There are compilers that are simply incredible in the code they produce. So as a general answer there are going to be many places where you can go into the output of the compiler and tweak the assembler for performance, and/or simply re-write the routine from scratch.
old_timer
GCC does extremely smart "platform-independent" optimisations. However, it is not so good at utilising particular instruction sets to their fullest. For such a portable compiler it does a very good job.
agreed. Its portability, languages coming in and targets going out are amazing. Being that portable can and does get in the way of being really good at one language or target. So the opportunities for a human to do better are there for a particular optimization on a specific target.
+1: GCC certainly isn't competitive at generating fast code but I'm not sure that is because it is portable. LLVM is portable and I've seen it generate code 4x faster than GCCs.
I prefer GCC, since it's been rock solid for many years, plus it's available for almost every platform that can run a modern portable compiler. Unfortunately I have not been able to build LLVM (Mac OS X/PPC), so I will probably not be able to switch to it. One of the good things about GCC is that if you write code that builds in GCC, you're most likely keeping close to the standards, and you will be sure that it can be built for almost any platform.
Longpoke, there is just one limitation: time. When you don't have the resources to optimize every single change to code and spend your time allocating registers, optimize few spills away and what not, the compiler will win every single time. You do your modification to the code, recompile and measure. Repeat if necessary.
Also, you can do a lot in the high-level side. Also, inspecting the resulting assembly may give the IMPRESSION that the code is crap, but in practice it will run faster than what you think would be quicker. Example:
int y = data[i]; // do some stuff here.. call_function(y, ...);
The compiler will read the data, push it to stack (spill) and later read from stack and pass as argument. Sounds shite? It might actually be very effective latency compensation and result in faster runtime.
// optimized version call_function(data[i], ...); // not so optimized after all..
The idea with the optimized version was, that we have reduced register pressure and avoid spilling. But in truth, the "shitty" version was faster!
Looking at the assembly code, just looking at the instructions and concluding: more instructions, slower, would be a misjudgment.
The thing here to pay attention is: many assembly experts think they know a lot, but know very little. The rules change from architecture to next, too. There is no silver-bullet x86 code, for example, which is always the fastest. These days is better to go by rules-of-thumb:
memory is slow
cache is fast
try to use cached better
how often you going to miss? do you have latency compensation strategy?
you can execute 10-100 ALU/FPU/SSE instructions for one single cache miss
application architecture is important..
.. but it does't help when the problem isn't in the architecture
Also, trusting too much into compiler magically transforming poorly-thought-out C/C++ code into "theoretically optimum" code is wishful thinking. You have to know the compiler and tool chain you use if you care about "performance" at this low-level.
Compilers in C/C++ are generally not very good at re-ordering sub-expressions because the functions have side effects, for starters. Functional languages don't suffer from this caveat but don't fit the current ecosystem that well. There are compiler options to allow relaxed precision rules which allow order of operations to be changed by the compiler/linker/code generator.
This topic is a bit of a dead-end; for most it's not relevant, and the rest, they know what they are doing already anyway.
It all boils down to this: "to understand what you are doing", it's a bit different from knowing what you are doing.
tiredcoder
Not the answer you're looking for? Browse other questions tagged c performance assembly or ask your own question.
Is C inefficient compared to Assembly?
Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?
Using Assembly Language in C/C++
INC instruction vs ADD 1: Does it matter?
Getting the high part of 64 bit integer multiplication
How to implement atoi using SIMD?
Can you decompile a game down to its original source code?
reason why custom loop is faster? bad compiler? unsafe custom code? luck?(lucky cache hits)
Is it possible to get better performance than a compiler by fully comprehending modern pc architecture?
_umul128 on Windows 32 bits
Why are elementwise additions much faster in separate loops than in a combined loop?
Why is processing a sorted array faster than processing an unsorted array?
Is < faster than <=?
\d less efficient than [0-9]
Why is printing "B" dramatically slower than printing "#"?
Which is faster: while(1) or while(2)?
Why is [] faster than list()?
Why is 2 * (i * i) faster than 2 * i * i in Java?
lang-c


Lets welcome 2019 together at the new and amazing Neelkanth Sarovar Premiere Hotel. Come and catch up and make new contacts and friends over some drinks. Experience the decadent sarova drums of heaven with sweet chili, and other exquisite food!
Meeting place is the Swirl Bar.
The Neelkanth Sarovar is located right after the traffic lights on Manchinchi Road opposite Mandahill Shopping Center.


Cumberland Consulting Group is a leading health- care consulting and services firm that helps some of the nation's largest payer, provider and life sciences organizations implement and optimize technologies to maximize operational efficiency. The Franklin, Tenn.-based firm offers clients comprehensive consulting services with a focus on strategic advisory, implementation, optimization and outsourcing. Founded in 2004, Cumberland began by providing IT consulting services to clients in a variety of industries with a focus on excellent client service, which remains one of our top priorities today. As the demand for strategic healthcare IT consulting services developed, we soon began focusing exclusively on the healthcare industry. "Our firm grew steadily and started receiving accolades from top industry publications and associations both for the quality of our client work and for creating a great place to work," says CEO Brian Cahill. In 2013, Cumberland acquired Mindlance Life Sciences, which diversified its client base to include pharmaceutical manufacturers. "We continued to expand our services to include specialized consulting resources through the acquisition of Cipe Consulting in 2014," Cahill says.
"Through the purchase of Oleen Pinnacle Healthcare Consulting in April 2016, we increased our presence in the payer market." Consulting caught up with Cahill to discuss the firm's financial performance.
Cahill: Our success is directly tied to the exceptional work of our highly-skilled consultants who deliver outstanding service to our clients on a daily basis. In addition, we've intentionally diversified our portfolio of services over that past few years to meet the demands of the provider, payer and life sciences healthcare verticals.
Consulting: How is this year shaping up for your firm? Cahill: We are having another great year. We've grown to 425- plus employees and have continued to introduce new services to meet our clients' needs.
Cahill: Next year's challenges will be similar to this year's—to continue to stay informed of changing regulations and new trends that impact our industry together, as well as to recruit and retain top talent.
Cahill: We're so pleased that Consulting magazine has chosen to recognize the hard work of our team and our growing client base by naming us one of the fastest-growing firms in the industry.


text:
3 Issues Women Around the World Confront in Common
March 21, 2011 by Andrea Newell
Women everywhere share common challenges.
Do women lack confidence? Is there a natural tendency to blame women victims in every culture? Do women in developed countries have similar problems as women in developing countries?
I recently attended the Women in the World 2011 Stories and Solutions summit. If you caught up with EcoSalon last week, you may have read our summit coverage on child trafficking and girls in sports. As I listened to the different topics, ranging from women on the front lines, to women business leaders, to a woman who wants to build a floating hospital on Lake Tanganyika, to Hillary Clinton's address, I noticed three persistent themes in the varied panel topics. Confidence. Victim-blaming. Strength.
Interestingly, confidence cut both ways. Women like Divya Keshav and Eva Walusimbi lit up as they told about how they started their own businesses and were able to contribute to their families and their communities. Divya built a thriving accessories business in Haiti with the help of Diane von Furstenberg before the earthquake wiped out her shop and all her hard work. Undeterred, she is in the process of rebuilding, strengthened by her previous success. Her growing confidence was plain to see due to the support and praise from von Furstenberg (who was also present at the summit).
Walusimbi is part of Solar Sister, an Avon-type women's business network supported by ExxonMobil's Women's Economic Opportunity that sells solar lights to rural residents in Uganda. She beamed as she told the audience how she helped women have safe lighting so they could extend their work day into the evening and girls could study after their chores were done. Other women from developing countries told similar stories of feeling immeasurable pride in themselves when they were supported and encouraged by others – whether they were starting a business, recovering from a trauma, or fighting for women's rights.
However, during at least two sessions, The Marzipan Layer and New Ways to Lead, the panelists talked about the tendency of women in the U.S. to lack confidence, to have difficulty negotiating for themselves, and to understate their worth during job negotiations. While women in developing countries, who are only beginning to be able to explore opportunities, are building their confidence in themselves, women in the U.S. who have many more opportunities, are seen as still suffering from a confidence problem.
Victim-Blaming
Victim-blaming is a universal issue. In Stealing Beauty, we met Yem Chhuon and her daughter, who were victims of an acid attack by her husband's mistress. The panelists explained that acid attacks are meant to severely injure, but not kill their victims, and they are carried out by both men and women. Acid is an easy weapon to get, and assault carries a light sentence, if it is even prosecuted.
Acid attacks are the equivalent of burning a scarlet letter onto victims' faces. Society's first instinct is to believe that the victim did something to deserve the attack, and since most often the victims' faces are affected, it is the first reaction they get from everyone they meet for the rest of their lives. If it sounds barbaric, that's because it is. But it has also arrived in the U.S. Even as we were learning about acid attacks in Manhattan, there was one reported the same day in Brooklyn. And it's not the first one in the U.S.
Other panels focused on the widespread problem of rape in developing countries and how to stop it, the cultural attitude that allows it, and the victim-blaming that accompanies it. However, that's an attitude that is present everywhere. Sadly, victim blaming is practically a recognized sport in the U.S. For every tragedy, there are people who respond from the heart, showing empathy and support, and there are always those who believe that somehow the victim brought it on herself. What was she wearing? What is her sexual history? These inappropriate and subtly accusatory questions are all too common.
Recently, there has been a furor over the victim-blaming of an 11-year-old victim in Texas who was raped by 17 men. Mother Jones took the New York Times to task over what it perceived as their victim-blaming reporting, but the residents of the town itself seemed more concerned about the effect this crime would have on the accused men (including two basketball stars and the son of a school board member) while few showed any sympathy for the child victim.
After CBS reported the sexual assault of CBS reporter Lara Logan in Egypt, a frenzy of public reaction swept across the Internet. Shockingly, several public figures showed little concern for Logan. Nir Rosen joked about Logan's assault on Twitter, saying she was "probably just groped, like thousands of other women," resulting in his dismissal from a fellowship at NYU. Debbie Schlussel publicized flagrantly cold-hearted comments on her blog including, "so sad, too bad, Laura." Even other reporters seemed to blame it on her looks. Some of her colleagues rallied to her defense, but they were all but drowned out by the controversy.
Many sites that reported on her assault were inundated with comments from readers ranging from insensitivity to claiming that it was her own fault for being there, and worse. NPR was forced to close their comments due to their inappropriate nature, and its editor scolded commenters equally for victim blaming and for vilifying all Egyptian and Arab men. Saying that she should not have been there because she is a woman, in my opinion, is still victim-blaming, dressed up in a benevolent chauvinism.
In our piece on child trafficking, we already discussed the victim-blaming attitude that persists for young girls. Evidently there are no circumstances where victims cannot somehow be blamed. There have been vicious tweets blaming the Japanese people for the recent earthquake. Hearing and reading about it everywhere has become profoundly depressing. Why is there such a persistent need to blame the victims of crimes, particularly women?
While there were grim stories shared at the Women in the World summit, there were also many stories of strength, bravery and accomplishment.
Condoleezza Rice and Madeleine Albright demonstrated that although their politics are vastly different, they have much in common in their support for women's rights and opportunities. They both called for more women to join politics and make their voices heard.
One of the most powerful moments of the summit was when Hillary Clinton spoke. She introduced a partnership between the Seven Sisters colleges (Barnard College, Bryn Mawr College, Mount Holyoke College, Radcliffe College, Smith College, Vassar College, and Wellesley College) and the U.S. State Department, to launch a new Women and Public Service Initiative – another milestone in her lifelong work on the behalf of women.
Host Tina Brown and other female titans such as Sheryl Sandberg, COO of Facebook, Zainab Salbi, Founder of Women for Women International, and Kirsten Gillibrand, U.S. Senator (NY) also demonstrated through their accomplishments that women today have more opportunities than at any other time in history. Yet, we still have so many obstacles to overcome, and there remains a vast divide between women and men on the uneven playing field of respect and common decency. In many ways, some attitudes toward women have not progressed much, even in developed countries.
Will Equality Solve These Problems?
How do we build confidence in all women, eliminate victim-blaming, and continue to celebrate women's strength and accomplishments? In Editor-in-Chief Tina Brown's debut issue of Newsweek, Kathleen Parker writes an article about how "women make lousy men." She posits the idea that women are striving so hard to be equal to men that they are losing sight of what it means to be a woman. That women are trying, in effect, not only to be as good as men, but to be men. "It turns out that women make lousy men, a fact for which we should feel grateful rather than apologetic."
She writes, "Women have tried to fit into a male-constructed world and found it either uninviting or inflexible to their needs." She goes on to say, "Until women are equal partners in the human race, we are less secure and surely less interesting…When women achieve parity in boardrooms and legislatures, they'll no longer have to twist into male versions of themselves but can help fashion a world that is a better fit for them and the human beings they create." Perhaps it is time to acknowledge that women are just as valuable as men, but their identities and needs will always be different. Maybe just that concession could make a difference in how women are perceived, treated, and appreciated.
As for the cure for victim blaming? I wish I knew.
Image: Wrote
Tags: Andrea Newell, feminism, Hillary Clinton, kathleen parker, News & Culture, newsweek, The Daily Beast, victim-blaming, women in the world
Andrea Newell
Andrea Newell is a Michigan-based writer specializing in corporate social responsibility, women's issues, and the environment.

redpajama_set_name: RedPajamaCommonCrawl


text:
Veteran turning 101 gets 5,000+ birthday cards
Updated: June 16, 2019, 8:47 p.m.
OREM, Utah (AP) — When John Frey's family requested 101 birthday cards to celebrate the World War II veteran's 101st birthday in Utah, they were expecting to get 500 at most.
At a celebration on June 8, a day after his birthday, Frey ended up with well over 5,000 cards, the Daily Herald reports.
According to the report, Frey's request spread quickly after The Associated Press picked up the story from the Daily Herald in May and it appeared in news outlets across the country.
The cards came from all 50 states and at least 12 countries. Entire classrooms of children, military veterans and Utah's elected officials wanted to wish the former mechanic/machinist for the U.S. Army a happy birthday.
Frey said he had not expected to ever get so many cards.
Jeanne Waters, the front desk receptionist at the Mervyn Sharp Bennion Central Utah Veterans Home where Frey lives, said she had to ask the Postal Service for an extra tub just to sort his cards every day.
"These have been overfilled with letters and packages and everything for him," Waters said. "It's been fun. It really has."
Frey celebrated with family and friends last week at home. His daughter Janice Carlson helped him use a letter opener to open one envelope including a sea shell and a note. "Holy mackerel!" Frey exclaimed after opening another card that played music.
Carlson said they are going to load up his room with as many cards as they can, but it will take a few days to open them all.
The excitement has been a bit tiring, Frey added.
"I just want to get in my car and take off for a while," said Frey, who lived in his own home until he was 100 and enjoys going for drives in his car.
Harris blasts Jeffrey Epstein then takes money from his law firm on same day
Senator: Bureau of Land Management moving from DC to Colorado
Trump administration abortion restrictions effective immediately


text:
10638 S. Cicero Ave,
Meet Dr. Forrest Tower
Dr. Tower's Recommendations Waterpik, Toothbrush & Floss
Partials and Dentures
Book an Appointment Emergency Dentistry
Dental Plaque: What You Need to Know
Plaque, like many oral health concerns, begins as a silent menace. You may recognize this colorless, sticky film as the fuzzy coating you feel when you first wake up.
For many people, a colorless film on the teeth may be the only sign. However, in some cases, more noticeable symptoms, such as receding gums or bad breath, occur.
What is plaque, and what causes it?
Plaque forms in your mouth throughout the day as you eat and drink and every night as you sleep when foods that contain carbohydrates (i.e., sugars and starches) are left on the teeth. Bacteria that live in the mouth feed on these foods and produce acids.
Plaque is known as a "biofilm" because it is actually a community of living microbes surrounded by a gluey polymer layer. The sticky coating helps the microbes attach to surfaces in the mouth, so they can grow into thriving micro-colonies.
How do I treat plaque?
Proactive dental care is the best way to manage plaque. This includes brushing and flossing your teeth regularly, limiting sugary foods and drinks, and seeing your Oak Lawn dentist twice a year to have plaque thoroughly removed. If brushing with a regular, soft-bristle brush isn't enough, you may want to consider using an electric toothbrush and/or adding a toothpaste that contains baking soda. Additionally, mouth rinses that contain small amounts of menthol, thyme, wintergreen, and eucalyptus oils, have been shown to help reduce plaque and gingivitis.
What happens if plaque isn't removed?
If plaque is not removed regularly when it's soft, it can combine with minerals from your saliva to create crystals that harden into tartar. Tartar, which generally has a yellow or brown color, builds up along the gumline on the front and back of your teeth. If left untreated, tartar can lead to a number of complications, including cavities and gum disease.
It's important to note that plaque that has hardened into tartar cannot be removed with regular brushing and must be scraped away by a dental professional. Our dentists and oral hygienists can remove this during your regular dental checkup and cleaning.
Contact Forrest Tower DDS today to schedule your next checkup!
Wednesday 1 PM - 8 PM
TowerDiver@rcn.com
© 2022 Forrest Tower DDS | Privacy Policy | Web Design, Digital Marketing & SEO By Adit


text:
'ALL GUNS BLAZING' FOR HALFORDS RACING WITH CATACLEAN AT OULTON PARK
Latest News posted 30th July 2021
After a productive two-day test earlier in the month – where on the second day the team topped the times – Halfords Racing with Cataclean is looking forward to another successful trip to Oulton Park this weekend (31 July/1 August).
Drivers Dan Rowbottom and Gordon Shedden will be hoping for a strong weekend on a circuit that has seen the team secure 12 podiums – including two wins and seven second-place finishes – over the past five years, after mixed results last time out at Brands Hatch.
"We showed our true pace at Brands, but we are still missing that elusive win so we'll be doing all we can this weekend to rectify that situation," said Team Manager, James Rogers. "The test earlier in the month was hampered by mixed conditions and it looks like we may well get that again at the weekend, so the good thing is we have an ultimate setup for each condition."
"Brands was full of highs and lows for me with my first BTCC career pole," added Rowbottom. "Unfortunately, the nerves got the better of me, so I didn't make the best of starts and dropped down the order. I was chuffed to pull off some pretty tough overtakes to fight back to third at the finish though.
"Overall, Brands was a good points haul for me, giving me a decent lead in the Jack Sears Trophy and leaving me seventh in the Drivers' Standings. I ran well at Oulton during the test and again really like this challenging, old school circuit, so I'll be doing my darndest to get more points on the board this weekend."
"I love Oulton," said Shedden. "It really reminds me of Knockhill. Up and down, tight and twisty, plus unforgiving if you get off the grey stuff. I was chuffed at Brands to get my highest place finish so far this season with second in the first race, but then lady luck left me again!
"I've gone well at Oulton in the past with nine podiums since 2010, so I'll be looking to replicate that again this weekend. It will also be great to see a full capacity crowd once again, we've missed having the fans as they give you a real boost."
WEEKEND WRAP-UP: OULTON PARK
Following the annual summer break, the 2021 Kwik Fit British Touring Car Championship got back underway at Oulton Park on…
INGRAM AIMING TO 'COME OUT OF THE BLOCKS FIGHTING' AS HE EXTENDS EXCELR8 PARTNERSHIP
Front-running Kwik Fit British Touring Car Championship driver Tom Ingram has boosted his pre-season preparations by prolonging his partnership with…
THE COOK REPORT
In case you missed it, Autosport's subscription platform, Autosport Plus, featured an article last week on all things Josh Cook!…


text:
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using NServiceKit.Common.Tests.Models;

namespace NServiceKit.OrmLite.FirebirdTests
{
    /// An ORM lite delete tests.
	[TestFixture]
	public class OrmLiteDeleteTests
		: OrmLiteTestBase
	{
        /// Sets the up.
		[SetUp]
		public void SetUp()
		{
			CreateNewDatabase();
		}

        /// Can delete from model with fields of different types table.
		[Test]
		public void Can_Delete_from_ModelWithFieldsOfDifferentTypes_table()
		{
            using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open())
			{
				db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);

				var rowIds = new List<int>(new[] { 1, 2, 3 });
				rowIds.ForEach(x => db.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));

				var rows = db.Select<ModelWithFieldsOfDifferentTypes>();
				var row2 = rows.First(x => x.Id == 2);

				db.Delete(row2);

				rows = db.GetByIds<ModelWithFieldsOfDifferentTypes>(rowIds);
				var dbRowIds = rows.ConvertAll(x => x.Id);

				Assert.That(dbRowIds, Is.EquivalentTo(new[] { 1, 3 }));
			}
		}

        ///
        /// Can delete by identifier from model with fields of different types table.
        ///
		[Test]
		public void Can_DeleteById_from_ModelWithFieldsOfDifferentTypes_table()
		{
            using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open())
			{
				db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);

				var rowIds = new List<int>(new[] { 1, 2, 3 });
				rowIds.ForEach(x => db.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));

				db.DeleteById<ModelWithFieldsOfDifferentTypes>(2);

				var rows = db.GetByIds<ModelWithFieldsOfDifferentTypes>(rowIds);
				var dbRowIds = rows.ConvertAll(x => x.Id);

				Assert.That(dbRowIds, Is.EquivalentTo(new[] { 1, 3 }));
			}
		}

        ///
        /// Can delete by identifiers from model with fields of different types table.
        ///
		[Test]
		public void Can_DeleteByIds_from_ModelWithFieldsOfDifferentTypes_table()
		{
            using (var db = new OrmLiteConnectionFactory(ConnectionString, FirebirdDialect.Provider).Open())
			{
				db.CreateTable<ModelWithFieldsOfDifferentTypes>(true);

				var rowIds = new List<int>(new[] { 1, 2, 3 });
				rowIds.ForEach(x => db.Insert(ModelWithFieldsOfDifferentTypes.Create(x)));

				db.DeleteByIds<ModelWithFieldsOfDifferentTypes>(new[] { 1, 3 });

				var rows = db.GetByIds<ModelWithFieldsOfDifferentTypes>(rowIds);
				var dbRowIds = rows.ConvertAll(x => x.Id);

				Assert.That(dbRowIds, Is.EquivalentTo(new[] { 2 }));
			}
		}

	}
}

redpajama_set_name: RedPajamaGithub


I rarely go online to read the established review sites partly due to erm not really anything happeing. DPR just pad out the news section with other items and phone reviews (Phil got out at the right time). IR not been there for some time either and Lula has gone subscription only you can no longer read all the artiles without that. Have to say most people I know are not buying much at all cameras or lenses wise.
Re: Camera sales still dropping..
the world economy still has not recovered from 2009. But I suspect one larger factor might be the fact that starting in 2012, 1.6 billion baby boomers began to retire and they are holding on to their money.
Me, I will buy an A99II if there is one, and maybe a couple of primes, but they will be Sigma art lenses. I have a Sony 24-70Z, a Minolta 24-85 and 28-85 and I can't see a serious difference in picture quality with any of them that makes the Sony worth 10 times the cost. I also have an A850 and A99 and in daylight still shots, I can't see a difference. In low light and action, like at an air show, the A99 is better, but not by light years.
Edward, I use the Minolta 24-85 which is a FF lens on my Sony A37, it gives superb sharpness because of the crop factor, same with my KM 17-35 f/2.8 D, both bought second hand for under a £100 each, I'm about to get a Tamron 17-50 F/2.8 as my standard kit lens.
Edward wrote: I have a Sony 24-70Z, a Minolta 24-85 and 28-85 and I can't see a serious difference in picture quality with any of them that makes the Sony worth 10 times the cost.
Well... probably the Sony-Zeiss 24-70 f2.8 is not "10 times better" than the Minolta 24-85 f3.5-4.5 (I do not have a way to measure it, and I think that it is unfair to do so unless you find a pristine new-old-stock copy of the Minolta lens) but the 24-70 really is a better lens.
I don't think there was anything unfair about my Minolta 24-85 comments. The sony 24-70 is a great lens, but also over-rated. I do happen to have a "pristine new-old-stock copy" of the Minolta and In low light the sony is better, but in most situations it is not a better lens then the Minolta. I also have a Sigma 12-24 and when I set the Sony and Sigma at 24mm for outside shots in daylight -- I can't tell from a picture which lens was used.
This year I "swapped" a Neewer E mount flash for a Sony HVL20M just to have a small flash in the bag when I don't want to take the larger flashes. If I am super honest bar a couple of exotic lenses I have the range well covered, there isn't really any obvious reaon to buy lenses purely for the sake of it.
The last purchase I made was the Tokina 11-16mm F2.8 and it is a lens which has now paid for itself and more by commercial jobs ie interior shots etc - I can't justify spending unless it's going to give me some return. As far as bodies go the current madness in the UK means it's probably going to get more expensive to buy products. Not that I can think of anything I really need. Maybe I'll buy a s/h FF body at some point. My current set up is more than adequate for my needs.
Still having fun with my relatively new A7 mk II. Bought the FE 24-70/4 as a walk around for it. Would like the FE 16-35/4 at some point. Then there are drones, monitors, printers, etc. etc. However school shoes and nappies have to take priority here at the moment .
Nex 5, Nex 6 (IR), A7M2, A99 and a bunch of lenses.
Edward wrote: I don't think there was anything unfair about my Minolta 24-85 comments.
Edward wrote: The sony 24-70 is a great lens, but also over-rated.
Well, no. IMHO the 24-70 f2.8 is not overrated. I didn't find anything special on this lens, until I use it on the A7R, where actually the 24-85 start showing it's limitations.
Edward wrote: I do happen to have a "pristine new-old-stock copy" of the Minolta and In low light the sony is better, but in most situations it is not a better lens then the Minolta. I also have a Sigma 12-24 and when I set the Sony and Sigma at 24mm for outside shots in daylight -- I can't tell from a picture which lens was used.
Yep. As I told you on my previous post, I don't think the Sony-Zeiss is 10 times better than the Minolta.
I purchased Sony's RX100M3 and A6000 last year for Alamy to replace RX100 (no viewfinder and prefer 24mm max. width) NEX-6 (menu and dark viewfinder). Franky, I am so delighted with these two cameras that I cannot imagine a need to trade up or replace any time soon. I am so amazed at the quality at 100% that I rarely reduce image size. 20/24Mp great for cropping. I think we have now reached a level of quality that only professionals needing the latest for their promotion need to upgrade. The same for software. I had a T&S lens with my Mamiya M/F years ago and was sorry to see it go when I went to DSLR only. With P/S Cloud there is no need to invest in such a lens. Adobe continue to send updates to LR/PS/Bridge Cloud, but we have reached the stage now that for me it is more features I don't need. I download in case some fixes or security features are included.
I would tend to agree the level of quality from images is probably at a point where there are no obvious reasons for most to upgrade. I didn't make the move to FF partly because I think I am satisfied with what I can get, though I might take a look at a cheaper body later on.
It's not a bad thing bar some awesome sensor revolution (again we are probably at good enough already, no doubt some organic sensors or other bits might turn up). The emphasis has shifted from the gear and tech to the results and that is not a bad thing at all. This does mean the review sites/magazines will have to shift away from reviews and more towards content. Magazines were mainly in that area from a long time ago; the online sites are probably on borrowed time as there are not enough new products to generate review content. Evidently DPR hasn't turned a profit for a long time.
I think most of the top most popular brands have now reached a plateau of image quality and performance, perhaps as Barry says start looking at the end product the PICTURE rather than constant deliverance on equipment, although I think a critical eye needs to be kept on lens performance which is now lagging behind.
My main criterion now is not so much the brand, but the whole available system which varies greatly from one brand to another.